挨拶 私は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がない
これは機能しません。コンソール: 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
コンソールで次のことを行うと、 'Operation.includes(:source).first .source.name'?未定義のメソッドをnilで取得しているので、これは、どのソースにもリンクされていないいくつかの 'Operation'オブジェクトがあることを示す指標になる可能性があります。これが当てはまり、それが意図的だった場合は、 '<%= operation.source? operation.source.name: "ソースなし"%> '。 –
Operation.includes(:source).first.source.nameはSource.nameを取得します。私はどのように私のビューでsource.nameを得ることができますか?ここに私の答えの解決策があります。しかし、あなたのアプローチを使ってsource.nameを取得する方法を知りたいです – ck3g