开发者

foreign key removed on new/build

hopefully someone can help me understand why this is happening. i setup the following instances...

@product = Product.find(params[:id])
@new_image = @product.images.new

when i debug @new_image, it correctly has the foreign key set.

--- !ruby/object:Image 
        attributes: 
          product_id: 1

however, when saving, the product_id was not being set. that's when i noticed that also in that debug info, was this...

changed_attributes: 
  product_id: 

basically nulling my foreign key. same thing if i use build. why isnt that instance not holding onto the foreign key?

UPDATE: to make things simpler, even if i just output debug Product.find(1).images.new in my vi开发者_如何学Cew, i get:

!ruby/object:ProductImage 
        attributes: 
          created_at: 
          product_id: 1
          updated_at: 
        attributes_cache: {}

        changed_attributes: 
          product_id: 
        destroyed: false
        marked_for_destruction: false
        new_record: true
        previously_changed: {}

        readonly: false


The way I understand it, your product's show view contains a form to post to the images controller. When you create the @new_image variable based on @product in your view, it properly assigned the product_id to the image. However, this does NOT persist when you post your form.

You have two options. The simplest would be to just add a <%= f.hidden_field :product_id %> item to your form, that way the product_id actually gets posted to Image#create. Alternatively, you could create a nested resource and do a <%= form_for [@product, @new_image] do |f| %> instead of the <%= form_for @new_image %> that you're probably using right now, and then in your create method do:

@product = Product.find(params[:product_id])
@new_image = @product.images.new(params[:image])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜