2012-05-08 13 views
0

私は2つの別々のDBテーブル、ユーザー、および製品を備えたレールアプリを持っています。ユーザーはhas_many製品を持ち、製品はユーザーに属しています。私のレールアプリでは、新製品の作成時に自動的にuserIDを添付できますか?

私は製品を作成するときに、製品表のuser_idデータベース列にuser_idを自動的に追加する必要があります。新しい製品が作成されたときに正しいuser_idが追加されるようにするために、自分のmvcにどのような変更を加える必要がありますか?

答えて

1

提案と同じように、以前の質問のいくつかの回答を受け入れることで、回答率が向上し、将来あなたの質問に回答する可能性が高くなります。

そこには、これを行うにはいくつかの方法が一つのアプローチ、以下のとおりです。

は、セキュリティ上の懸念を認識していることを確認し、現在のユーザ機能

class ApplicationController < ActionController::Base 
    private 
    # Finds the User with the ID stored in the session with the key 
    # :current_user_id This is a common way to handle user login in 
    # a Rails application; logging in sets the session value and 
    # logging out removes it. 
    def current_user 
    @_current_user ||= session[:current_user_id] && 
     User.find_by_id(session[:current_user_id]) 
    end 
end 

http://guides.rubyonrails.org/action_controller_overview.html#session

を作成します。 Deviseのような宝石も手助けすることができます。製品コントローラ

class ProductsController < ApplicationController 
    def create 
    current_user.products.create! params[:product] # make sure attr_accessible is setup on products 
    end 
end 

追加

3

ユーザーは、新しい製品の作成をスコープできます。例えば、これに代えて

Product.create(params[:product]) 

あなたがこれを行う: "CURRENT_USER" は、製品を作成しているユーザである

current_user.products.create(params[:product]) 

を。

関連する問題