has_many-belongs_to 关联的问题
我的数据基本上是画廊有很多图片,并且图片属于画廊。图片表具有外键“gallery_id”。
虽然我之前使用过 has_many 和 Belongs_to 关联,所以我不确定我做错了什么。
这些是我的相关模型:
class Gallery < ActiveRecord::Base
attr_accessible :name
has_many :pictures
belongs_to :home
end
class Picture < ActiveRecord::Base
belongs_to :gallery
validates :image, :presence => true
mount_uploader :image, ImageUploader
end
如果我这样做:
gallery = Gallery.create(:name => 'some name')
picture = Picture.create(:name => 'some name' , :image => 'some_image')
picture.gallery = gallery
这是真的:
picture.gallery == @gallery
但这不是
gallery.pictures == [ picture ]
因为 gallery.pictures 返回一个空数组。
另一方面,如果我以这种方式创建图片,一切都会按预期进行:
picture = Picture.create(:name => 'some name' , :image => 'some_image', :gallery_id => gallery)
为什么?我做错了什么?我正在使用 Rails 3.1.1 和 sqlite
My data is basically Gallery(s) have many Picture(s), and Picture(s) belong_to a gallery. the pictures table has the foreign_key 'gallery_id'.
Although I`ve used has_many and belongs_to associations before, so I am not sure what I am doing wrong.
These are my relevant models:
class Gallery < ActiveRecord::Base
attr_accessible :name
has_many :pictures
belongs_to :home
end
class Picture < ActiveRecord::Base
belongs_to :gallery
validates :image, :presence => true
mount_uploader :image, ImageUploader
end
If I do this:
gallery = Gallery.create(:name => 'some name')
picture = Picture.create(:name => 'some name' , :image => 'some_image')
picture.gallery = gallery
this is true:
picture.gallery == @gallery
but this isnt
gallery.pictures == [ picture ]
because gallery.pictures returns an empty array.
On the other hand, if I create the picture this way, everything works as expected:
picture = Picture.create(:name => 'some name' , :image => 'some_image', :gallery_id => gallery)
Why? What I am doing wrong? I am using Rails 3.1.1 and sqlite
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它应该有效
it should work
将图片添加到图库时。尝试以相反的方式完成作业。
这将更新
#pictures
方法以返回新分配的图片。When adding pictures to your gallery. Try doing the assignment the other way around.
This will update the
#pictures
method to return the newly assigned picture.