访问属于另一个模型的模型

时间:2014-06-30 20:45:09

标签: ruby-on-rails ruby rails-activerecord

我有一个'画廊'模型,它与'Exhbition Images'有'has_many'关系(并且反对属于belongs_to)。

我想通过Gallery模型显示与每个图库相关联的图像。但是我遇到了错误

undefined method `exhibition_images' for #<Gallery::ActiveRecord_Relation:0x00000108159dd0>

当我尝试实现这行代码时

gallery index:

<%= @gallery.exhibition_images.each do |exhibition_image| %>
  <%= exhibition_image.title %>
<% end %>

我确信这很简单,我遗漏了一些明显的东西。

画廊控制器

def index
  @gallery = Gallery.all
end

图库模型

    class Gallery < ActiveRecord::Base
    extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :guide
has_many :exhibition_images
accepts_nested_attributes_for :exhibition_images
    end

展览图片

class ExhibitionImage < ActiveRecord::Base
belongs_to :gallery

has_attached_file :image, styles: { small: "100x100", guide: "500x500" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

end

SCHEMA

create_table "exhibition_images", force: true do |t|
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"
t.integer  "gallery_id"
t.datetime "created_at"
t.datetime "updated_at"

create_table "galleries", force: true do |t|
t.string   "title"
t.string   "slug"
t.integer  "guide_id"
t.datetime "created_at"
t.datetime "updated_at"
end

2 个答案:

答案 0 :(得分:2)

undefined method `exhibition_images' for #<Gallery::ActiveRecord_Relation:0x00000108159dd0>

您正试图访问exhibition_images上的ActiveRecord::Relation。你有一个关系对象,因为你正在调用:

@gallery = Gallery.all

这为您提供了一个范围,您可以使用该范围将更多查询条件链接在一起。您需要获取单个图库对象才能调用exhibition_images。您可以通过在first上调用@gallery来执行此操作,或者您需要执行查询并迭代结果:

<%= @gallery.each do |gallery| %>
  gallery.exhibition_images.each do |exhibition_image| %>
    <%= exhibition_image.title %>
  <% end %>
<% end %>

但是,如果你这样做,我一定要急切加载exhibition_images

@gallery = Gallery.includes(:exhibition_images).all

答案 1 :(得分:1)

问题是@gallery包含一个Gallery对象数组。

在您的控制器中,您应该:

@galleries = Gallery.all

然后迭代@galleries数组

<% for gallery in @galleries %>
  <%= gallery.exhibition_images.each do |exhibition_image| %>
    <%= exhibition_image.title %>
  <% end %>
<% end %>