Rails:根据模型关联循环遍历db对象

时间:2018-03-15 14:18:46

标签: ruby-on-rails ruby

我有两个模型post.rbattachment.rb,其中包含以下关联:

class Attachment < ApplicationRecord
  belongs_to :post, optional: true
end

class Post < ApplicationRecord
  has_many :attachments, :dependent => :destroy
end

这就是我在视图所在的控制器操作中所拥有的:

 def results_search
    if params[:search]
      @attachment = Attachment.all
      @posts = Post.search(params[:search])
   end
 end

我试图执行此操作<% @posts.attachments.each do |post|%>,但我收到以下错误undefined method attachments' for #<Post::ActiveRecord_Relation:0x007fa673bef9d0>

我想循环搜索所有结果(@posts),并将结果显示在每个帖子的附件旁边。每个附件都分配了post_id。我有什么想法可以实现这个吗?

1 个答案:

答案 0 :(得分:4)

你会想做类似的事情:

@posts.each do |post|
  # do some stuff with post (show name, content, etc.)
  post.attachments.each do |attachment|
    # do stuff with attachment (show, etc.)
  end
end 

真正的样子取决于你在做什么(查看?)以及你正在使用什么工具(vanilla erb,slim,haml等)。

此外,你会想要做一些急切的加载,所以你不会在N + 1的土地上结束。