在新建/构建时删除外键
希望有人可以帮助我理解为什么会发生这种情况。我设置了以下实例...
@product = Product.find(params[:id])
@new_image = @product.images.new
当我调试@new_image时,它正确地设置了外键。
--- !ruby/object:Image
attributes:
product_id: 1
但是,保存时,未设置product_id
。就在那时我注意到在调试信息中,这...
changed_attributes:
product_id:
基本上使我的外键无效。如果我使用构建,同样的事情。为什么该实例不保留外键?
更新: 为了让事情变得更简单,即使我只是在我的视图中输出 debug Product.find(1).images.new
,我得到:
!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
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 view, 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解,您产品的
show
视图包含一个要发布到images
控制器的表单。当您在视图中基于@product
创建@new_image
变量时,它会正确地将product_id
分配给图像。但是,当您发布表单时,这种情况不会持续存在。你有两个选择。最简单的方法是在表单中添加一个
<%= f.hidden_field :product_id %>
项,这样,product_id 实际上就会发布到Image#create
。或者,您可以创建一个嵌套资源并执行<%= form_for [@product, @new_image] do |f| %>
而不是您现在可能正在使用的<%= form_for @new_image %>
,然后在您的create
方法中执行:The way I understand it, your product's
show
view contains a form to post to theimages
controller. When you create the@new_image
variable based on@product
in your view, it properly assigned theproduct_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 toImage#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 yourcreate
method do: