has_many-belongs_to 关联的问题

发布于 2024-12-12 14:35:56 字数 1005 浏览 0 评论 0原文

我的数据基本上是画廊有很多图片,并且图片属于画廊。图片表具有外键“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

中性美 2024-12-19 14:35:56

它应该有效

gallery.pictures.create :name => 'some name' , :image => 'some_image'

it should work

gallery.pictures.create :name => 'some name' , :image => 'some_image'
固执像三岁 2024-12-19 14:35:56

将图片添加到图库时。尝试以相反的方式完成作业。

gallery = Gallery.create(:name => 'some name')
picture = Picture.create(:name => 'some name' , :image => 'some_image')
gallery.pictures << picture

这将更新 #pictures 方法以返回新分配的图片。

When adding pictures to your gallery. Try doing the assignment the other way around.

gallery = Gallery.create(:name => 'some name')
picture = Picture.create(:name => 'some name' , :image => 'some_image')
gallery.pictures << picture

This will update the #pictures method to return the newly assigned picture.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文