1

写真モデルと製品モデルがあります。

製品コントローラーの作成アクションで、関連付けられていないすべての写真を見つけて、現在の製品に接続したいと考えています。製品IDがnilである現在のユーザーに属するすべての写真を見つけようとしています。

次に、写真ごとに製品 ID を @product.id に設定します。

私は何をすべきか?

def create
  @product = current_user.products.create(params[:product])
    if @product.save
      render "show", notice: "Product created!"

      # code here 

    else
      render "new", error: "Error submitting product"
    end
  end

   def current_user
    @current_user ||= User.find_by_auth_token(cookies[:auth_token]) 
  end

schema.rb

create_table "photos", :force => true do |t|
  t.integer  "product_id"
  t.integer  "user_id"
end

create_table "products", :force => true do |t|
  t.string   "name"
  t.integer  "user_id"
end
4

2 に答える 2

1

最初に、 createの代わりにbuildを使用して、product のインスタンスを構築する必要があります。そうしないと、次の行は無意味になります。したがって、コードは次のようになります。if @product.save

def create
  @product = current_user.products.build(params[:product]) # using build to construct the instance
  if @product.save
    render "show", notice: "Product created!"

    # Update un-related Photos
    Photo.where(:product_id => nil).update_all(:product_id => @product.id) 

  else
   render "new", error: "Error submitting product"
  end
end
于 2013-07-15T08:00:18.347 に答える
1

組織の場合、Productモデルでこれを行う必要があります。

class Product

  before_save :set_unassigned_photos

  def set_unassigned_photos
    self.photos = user.photos.unassigned
  end

そしてPhotoモデルでは:

class Photo

  scope :unassigned, where(product_id: nil)

このようにして、シンコントローラーのファットモデルの「提案」に従います。コントローラーはそのまま残ります。

于 2013-07-15T08:01:02.153 に答える