2016-10-09 8 views
1

Railsの質問...Rails Activerecordが値を返さない

ビュー内でデータベースに結合されたいくつかのテーブルからデータを出力しようとしています。具体的には、私は、各プロパティのアドレス(プロパティモデルから「アドレス」)をプリントアウトしたい、それが

質問に対応するコメント(金利モデルから「COMMENT_TEXT」)です。今私はテーブルを結合してい

1)景色;しかし、私はこれが正しいとは思っていませんが、コントローラーに参加させる方法は不明です。私はビューの中のテーブルにまったく参加する必要がありますか?それともコントローラーでこれが起こっているのでしょうか?

2)私の見解では、アドレスとそれに対応するcomment_textを印刷したいと思います。ただし、今すぐ印刷しようとすると、アクティブなレコード関係オブジェクトのように見えます。「["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 

コントローラー:

def index 
    @properties = Property.all 
end 

ビュー:

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

答えて

1

1)今、私はビューでテーブルを結合しています。しかし、私はこれが正しいとは思っていませんが、コントローラーに参加させる方法は不明です。私はビューの中のテーブルにまったく参加する必要がありますか?それともコントローラーでこれが起こっているのでしょうか?

回答は意見に基づいています。いくつかの人々は、様々なresonsのビュー内のDBクエリを好む。たとえば、ビューをキャッシュすることができますので、データベースをクエリしません。他の人は、それがより良いテストのような他の理由でビューに属していないと言います。だからあなたは自由に道を選ぶことも、道をたどることも自由です。

2)すなわち示す "[" テスト "]" 私はそれが配列を返すp.interests.collect(&:comment_text) "試験"

を表示します。 Erbはp.interests.collect(&:comment_text).to_sを間接的に呼び出して、あなたが見えるようにします。

異なる出力が必要な場合は、comment_textsを反復処理する必要があります。

+0

おかげでslowjack

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

参考!どのように私はそれを逃したか分からないが、それは働いた! – Anthony

0

include.Withを使用すると、アクティブレコードによってすべての指定された関連付けが最小限のクエリ数でロードされることが保証されます。

EX- コントローラー:

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

ビュー:ActiveRecord QueryMethods

関連する問題