Access another models value within a view, simple but complex?
I have a simple problem, but finding the solution is NOT that simple.
I have two models, Person, Skill
Person has many skills Skills belong to personIn the database, Person table has a skill_id which takes the id from the Skills table as foreign key.
In the view I am trying to list the skills for that Person by name, I can get them by id, but how can I retrieve the name field from the Skills table.
Person.html(view)
<p>Current skills for: <b><%= "#{ @person.name }" -%></b></p>
<% @people.each do |p| %>
<p>Age: <%= "#{p.age}开发者_如何学C" %></p>
<p><%= "#{p.start_date}" %></p>
<p><%= "#{p.skill_id}" %></p>
<% end %>
You say you've got has_many :skills
. but then you go on to say that you've got a skill_id
on a the persons
table, which is incongruent. Which is it that you want?
Do you want a person to have a single specific skill in which case then what you've got now database-wise is fine, but model wise is not. The Person
model in this case would have to have belongs_to :skill
and the Skill
model would have to have has_many :people
The other possible way around I can think that you'd want it is that a person has_and_belongs_to_many :skills
and a skill has_and_belongs_to_many :people
. This will allow many people to have many skills, which is what I truly think you want. Then in the view, you can do this:
<% people.each do |p| %>
<h2><%= p.name %>'s skills</h2>
<% p.skills.each do |skill| %>
<%= skill.name %>
<% end %>
<% end %>
So which is it? Your question says one thing and then the polar opposite which is greatly confusing. I hope this answer will help you make the right choice.
<% @people.each do |p| %>
<% p.skills.each do |s| %>
<%= s.name %>
<% end %>
<% end %>
You current model design does not support requirement, i.e.
Skill belongs to multiple Person
Person has many skills
This is good case for many-to-many association. You have introduce a bridge table to hold the association.
class Person
has_many :person_skills
has_many :skills, :through => :person_skills
end
class Skill
has_many :person_skills
has_many :person, :through => :person_skills
end
# person_skills table with person_id and skill_id columns
class PersonSkill
belongs_to :person
belongs_to :skill
end
To get the skills of a person by name:
@person.skills.find_all_by_name("foo")
@person.skills.all(:conditions => ["name LIKE ?", "foo%"])
精彩评论