2011-07-17 5 views
0

私の製品にコントローラのuser_id、Location_id、product_dates_idを与えるにはどうすればいいですか?コントローラのクラスに、それが属するIDをどのようにクラスに与えますか?

class Product < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :location 
    belongs_to :product_date 
end 

マイコントローラー:

def new 
    @location = Location.new 
    @product = Product.new 
    product_date = @location.product_dates.build 
    product_date.products.build 
end 

def create 
    @location = Location.new(params[:location]) 
end 

マイ表:

create_table :products do |t| 
     t.integer :user_id 
     t.integer :location_id 
     t.integer :product_date_id 
end 

ありがとうございました。

答えて

1

をproduct_dateフォームの中のfields_for宣言は関連オブジェクトのデータがpoのときに製品のハッシュの中にネストされるように調整するので、作成と更新のアクションは変更を必要としません作成アクションと更新アクションに戻ります。 accepts_nested_attributes_forすべての右のモデルの宣言とすべてに自動的に更新されること

カップルは/あなたの質問に答える

を作成しました。新しいアクションはすべてのレコードを作成し、すべての関連付けを設定しますが、製品に関連付けられた場所に既に関連付けられているため、製品に関連付けられたproduct_dateは実際には必要ないようですロケーションには多くの製品(元の新しいアクションに基づく仮定)があることがあります。多くのロケーションレコードからのproduct_dateと関連するproduct_dateレコードを製品に直接追加する必要があります。

私はあなたに少し間違っていると思います。

ます。また、製品モデル上のクラスのメソッドに新しいアクションが

@product = Product.new_with_associations(current_user) 

としてだけでかなり多くを行うと全く同じに必要self.new_with_associations defのような何かをすることができますすることをリファクタリングを検討すべきである

コード私は新しいアクションのためにあなたを与えましたが、非常に正当な理由でセッションハッシュ(current_userが最終的に来る場所)としてパラメータとしてcurrent_userを渡す必要があります。

これを製品のクラスメソッドに入れると、コントローラコードがクリーンアップされるだけでなく、コードが再利用可能になり、コンソールとテストスイートの両方からテストできるようになります

2
@location = Location.create(params[:location]) 
@location.products.each{ |p| p.update_attribute :user_id, current_user.id } 
@location.product_dates.map(&:products).flatten.each{ |p| p.update_attribute :user_id, current_user.id } 

またはより良い

def new 
    #First create the new product object assuming you have a current_user available. If not you will need to make a current_)user available. 
    @product = current_user.build_product 
    #Now build a new location for the product 
    location = @product.build_location # You don't need location to be an instance variable. 
    #when you reference @location in your form you should now be using fields_for :locations instead. 
    #build a new product_date object for the location_product_dates array 
    product_date = @location.product_dates.build 
    #Now add that product date object to the product 
    product.product_date = product_date 
end 

は、関連する製品形態に宣言fields_for関連のモデルにaccepts_nested_attributes宣言を追加し、使用し、あなたの質問に答えるために、各製品に:user_idのための隠しフィールドを追加し、

関連する問題