2011-01-26 22 views
0

挨拶 私は3デシベルのテーブルを持っているRuby on Railsにに参加します id 私は(足場によって生成された)データを取得するためのコードビューのは使用:</p> <p><strong>がタイプ</strong> ID 名</p> <p><strong>ソース</strong> ID</p> <p><strong>操作</strong>をTYPE_ID 名:3つの

@operations = Operation.all 

ピースを持って操作#・インデックス・コントローラで

class Type < ActiveRecord::Base 
    has_many :sources, :dependent => :destroy 
end 

class Source < ActiveRecord::Base 
    belongs_to :type 
    has_many :operations, :dependent => :destroy 
end 

class Operation < ActiveRecord::Base 
    belongs_to :source 
    default_scope :order => 'created_at DESC' 
end 

: コメント ...

それぞれの

とモデルをsource_idをoperations/index.html.erb足場でも生成

<% @operations.each do |operation| %> 
    <tr> 
    <td><%= operation.source_id %></td> 
    <td><%= operation.comment %></td> 
    </tr> 
<% end %> 

今、私はsource.nameの代わりに、* operation.source_idを使用したい*

私が実行しようとしました:

-replaceは#は動作しませんoperation.sources.nameするoperation.source_id

を使用して-tried:加入、およびソーステーブルのフィールドに

irb(main):057:0> Operation.first(:joins => :source) 
=> #<Operation id: 2088, source_id: 1, summ: 10.0, comment: "", created_at: "2011-01-01 07:39:45", updated_at: nil> 

または

を取得することはできません
irb(main):063:0> Operation.first(:joins => 'INNER JOIN sources ON operations.source_id = sources.id') 
=> #<Operation id: 2088, source_id: 1, summ: 10.0, comment: "", created_at: "2011-01-01 07:39:45", updated_at: nil> 

どうすれば正しく使用する必要がありますか:追加フィールドを追加するには、に参加しますか? または、テーブルデータを結合する別の方法があります。

そして、なぜ/ show.html.erb操作で、私は<% = @ operation.source.name%>を使用し、正常にsource.nameが、*操作/インデックスにを得ることができます。 html.erの* bがない

答えて

2
<% @operations.each do |operation| %> 
    <tr> 
    <td><%= operation.source.name %></td> 
    <td><%= operation.comment %></td> 
    </tr> 
<% end %> 

私も(すなわち、個々の操作のソース用に別のデータベースクエリを実行している)N + 1の状況を避けるためにincludes文を使用するように#index方法を変更することをお勧めしたいことができます。

@operations = Operation.includes(:source).all 
+0

これは機能しません。コンソール: irb(main):011:0 * Operation.includes(:source).first =>#<操作ID:2088、source_id:1、summ:10.0、コメント: ""、created_at: "2011- 0100 07:39:45 "、updated_at:nil> ブラウザ: 未定義メソッド' name 'for nil:NilClass – ck3g

+0

コンソールで次のことを行うと、 'Operation.includes(:source).first .source.name'?未定義のメソッドをnilで取得しているので、これは、どのソースにもリンクされていないいくつかの 'Operation'オブジェクトがあることを示す指標になる可能性があります。これが当てはまり、それが意図的だった場合は、 '<%= operation.source? operation.source.name: "ソースなし"%> '。 –

+0

Operation.includes(:source).first.source.nameはSource.nameを取得します。私はどのように私のビューでsource.nameを得ることができますか?ここに私の答えの解決策があります。しかし、あなたのアプローチを使ってsource.nameを取得する方法を知りたいです – ck3g

0

は解決:

opearions#インデックス

@operations = Operation.all :joins => :source, :select => '*' 

操作/ index.htmlをします。erb

<% @operations.each do |operation| %> 
    <tr> 
    <td><%= operation.name %></td> 
... 
+0

これはうまくいくかもしれませんが、本当に "Railsの方法"ではありません。私は説明したdmarkowのようにすることをお勧めします。それは本当にうまくいくはずです。 – DanneManne

関連する問題