开发者

Question about associating models

I'm working on a Dungeons and Dragons character database. I have two models, character and statistic. I want this to work where each character has one set of statistics. The problem is, when I create a new character, every character shares the same statistic information. This is probably a really easy problem to solve, but I've been butting my head up against it and can't figure it out.

Here's code from the character model:

class Character < ActiveRecord::Base

  has_many :statistics, :dependent => :destroy

end

Here's code from the statistic model:

class Statistic < ActiveRecord::Base

  bel开发者_运维问答ongs_to :character

end

What's the proper code for displaying the statistic model when viewing the character? Do I need to use a link_to or a render tag? Thanks!


Since there is many of them, you'll need to use a loop or something:

<ul>
  <% @character.statistics.each do |stat| %>
    <li><%= stat %></li>
  <% end %>
</ul>

Even better would be to use a partial:

<ul>
  <% @character.statistics.each do |stat| %>
    <%= render :partial => "characters/statistic", :object => stat %>
  <% end %>
</ul>

Then you'll have app/views/characters/_statistic.html.erb:

<li><%= statistic %></li>

This way you can use the code for the statistic rendering in other places too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜