2016-10-09 41 views
1

Rails的问题...Rails的Activerecord不返回值

我想从我的数据库在视图中连接在一起的几个表中打印数据。具体而言,我想打印出各个属性地址(房产模型“地址”),它的相应的注释(从利益型“COMMENT_TEXT”)

问题:

1)现在我加盟的表风景;不过,我认为这是不正确的,但我不确定如何将它们加入控制器。我应该加入视图内的表吗?或者应该在控制器中发生这种情况?

2)在我的视图中,我想打印出地址和相应的comment_text;然而,当我尝试打印出现在,它看起来像一个活跃的记录关系对象,即显示“[”测试“]”,我希望它显示“测试”

任何想法?下面的代码:


模式:

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 

控制器:

def index 
    @properties = Property.all 
end 

查看:

<% @properties.each do |p| %> 
    <td><%= p.interests.collect(&:comment_text) %> 
<% end %> 

回答

1

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

答案是基于意见的。有些人赞同视图中的DB-Queries以获得各种权限。例如视图可以被缓存,所以你不会查询你的数据库。其他人认为它不属于其他原因,比如更好的测试。所以你可以自由选择或遵循路径。

2),即显示 “[” 测试 “]”,我想它显示 “测试”

p.interests.collect(&:comment_text)返回一个数组。 Erb间接呼叫p.interests.collect(&:comment_text).to_s,这样你就能看到你所看到的。

如果你想要一个不同的输出,你必须迭代你的comment_texts。

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

感谢slowjack!不知道我是如何错过的,但工作! – Anthony

0

我想,如果你使用include.With包括,活动记录,确保所有指定的协会使用的查询的最小可能数加载这将是巨大的。

EX- 控制器:

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

观点:

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

参考ActiveRecord QueryMethods

相关问题