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 endHere's code from the statistic model:
class Statistic < ActiveRecord::Base
bel开发者_运维问答ongs_to :character endWhat'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.
精彩评论