belongs_to :モデル名このようにモデルクラスに記述するだけです。例として、Goodクラスにbelongs_toを追加したサンプルを下のリスト欄に掲載しておきました。これで、Goodから、関連するMakerを取り出すことができるようになります。
<%= good.maker.name %>このように、makerプロパティのnameを出力していることがわかります。先ほどのmaker.goodとまったく同様に、ここではgoodに「maker」というプロパティが用意され、そこに関連するMakerインスタンスが設定されているのです。
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※Goodクラスの修正 class Good < ActiveRecord::Base attr_accessible :maker_id, :memo, :name, :price, :star belongs_to :maker end ※index.html.erbの修正 <table> <tr> <th>Name</th> <th>Maker</th> <th>Price</th> <th>Star</th> <th>Memo</th> <th></th> <th></th> <th></th> </tr> <% @goods.each do |good| %> <tr> <td><%= good.name %></td> <td><% if good.maker != nil %> <%= good.maker.name %> <% end %></td> <td><%= good.price %></td> <td><%= good.star %></td> <td><%= good.memo %></td> <td><%= link_to 'Show', good %></td> <td><%= link_to 'Edit', edit_good_path(good) %></td> <td><%= link_to 'Destroy', good, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </table>
<< 前へ |