Ruby on rails Rails Activerecord不返回值

Ruby on rails Rails Activerecord不返回值,ruby-on-rails,join,activerecord,Ruby On Rails,Join,Activerecord,铁路问题 我正在尝试打印视图中数据库中连接在一起的几个表中的数据。具体来说,我想打印出每个属性地址(“属性模型中的地址”)及其相应的注释(“兴趣模型中的注释文本”) 问题: 1) 现在我正在视图中加入表格;然而,我认为这是不正确的,但我不确定如何将它们加入控制器。我应该在视图中加入表吗?或者这应该发生在控制器中 2) 在我看来,我想打印出地址和相应的评论文本;但是,当我现在尝试打印时,它看起来像一个活动记录关系对象,即显示“[“test”]”,我希望它显示“test” 有什么想法吗?代码如下:

铁路问题

我正在尝试打印视图中数据库中连接在一起的几个表中的数据。具体来说,我想打印出每个属性地址(“属性模型中的地址”)及其相应的注释(“兴趣模型中的注释文本”)

问题:

1) 现在我正在视图中加入表格;然而,我认为这是不正确的,但我不确定如何将它们加入控制器。我应该在视图中加入表吗?或者这应该发生在控制器中

2) 在我看来,我想打印出地址和相应的评论文本;但是,当我现在尝试打印时,它看起来像一个活动记录关系对象,即显示“[“test”]”,我希望它显示“test”

有什么想法吗?代码如下:


模式:

create_table "interests", force: :cascade do |t|
  t.integer  "user_id"
  t.integer  "property_id"
  t.string   "interested",   default: "unknown"
  t.string   "comment_text"
  t.datetime "created_at",                       null: false
  t.datetime "updated_at",                       null: false
end

add_index "interests", ["property_id"], name: "index_interests_on_property_id"
add_index "interests", ["user_id"], name: "index_interests_on_user_id"

create_table "properties", force: :cascade do |t|
  t.string   "address"
  t.string   "city"
  t.string   "state"
  t.integer  "zip"
  t.datetime "created_at",                             null: false
  t.datetime "updated_at",                             null: false
end
型号:

class Property < ActiveRecord::Base
  has_many :interests
  has_many :users, through: :interests

  default_scope {order("id ASC")}
end

class Interest < ActiveRecord::Base
  belongs_to :property
  belongs_to :user

  validates :user_id, :presence => true
  validates :property_id, :presence => true
end
视图:


1) 现在我正在视图中加入表格;然而,我认为这是不正确的,但我不确定如何将它们加入控制器。我应该在视图中加入表吗?或者这应该发生在控制器中

答案是基于意见的。有些人出于各种原因喜欢视图中的DB查询。例如,视图可以缓存,因此您不需要查询数据库。其他人说,由于其他原因,比如更好的测试,它不属于这个观点。所以你可以自由选择或走一条路

2) 例如,显示“[“test”]”,我希望它显示“test”

p.interests.collect(&:comment\u text)
返回一个数组。Erb确实会间接地调用
p.interests.collect(&:comment\u text.),以获得所看到的内容

如果你想要一个不同的输出,你必须迭代你的评论文本

<% @properties.each do |property| %>
     property.interests.each do |interest|
        <td><%=interest.comment_text %>
    <% end %>
<% end %>

财产、利益、每个人都有利益|

我认为如果您使用include就太好了。使用include,Active Record可以确保使用尽可能少的查询数量加载所有指定的关联

前- 控制器:

def index
  @properties = Property.all
end
def index
 @properties = Property.includes(:interests)
end
视图:


财产、利益、每个人都有利益|

Ref

谢谢slowjack!我不知道我怎么会错过,但这很有效!
def index
 @properties = Property.includes(:interests)
end
<% @properties.each do |property| %>
  property.interests.each do |interest|
    <td><%=interest.comment_text %>
 <% end %>
<% end %>