开发者

Display child values in parent view

I am really having trouble with what I would think is a relatively easy problem, and probably very easily rectified with something I am perhaps doing wrongly.

I have a Person model, and a Department model.

The relationships are a Person has_one :department, and Department belongs_to :person

In my view, when I'm looping to gather the person's attributes, I want to be able to access the Department name. I have the department_id as a foreign key in the Person table, so I can see the valid ID for each persons department, but how can I point this id to retrieve the department name.

<% @people.each do |p| %>
    <%= p.name %>
    <%= p.tel_num %>
    <%= p.department_id %>   <- i want this to somehow display the name of department
<% end %>

I have tried various things, p.department.name, p.department_id.name

NO LUCK!!

Very frustrating because I know its a very easy issue.

Any help much 开发者_StackOverflowappreciated.


Update:

Sure heres my code:

Department model:

Class Department < ActiveRecord::Base
    has_one :person
end

Person model:

Class Person < ActiveRecord::BAse
    belongs_to :department
end

Show Person View:

<% @people.each do |p| %>
<p>Name: <%= "#{p.name}" %> </p>
<p>Start Date: <%= "#{p.start_date}" %> </p>
<p>Current Department: <%= "#{p.department_id}" %> <- displays relevant id
<% end %>

The person_department_id is being returned as 2, which would relate to "Accounts" in the department table, so thats fine.

When altering to your relations, and amending the view to: <%= p.department.name %> I still get the

undefined method `department' for #<Person:0x47f9040>


You've got relationship (hasone-belongsto) opposite way. Foreign key is supposed to be on 'belonging' side, department in your case.

So, you'll have to either update your database schema or switch has_one and belongs_to in your models.

You can read more on the subject here.

PS Also worth noting, it's very strange organization where every department consist of exactly one person.

edit On new data
You're inconsistent in your code. You used p.department_id in original post and p.person_department_id later.
Note, rails can't read foreign key name from your mind, so modelname_id is assumed by default. If you want something different, specify value explicitly.

Also, please do post updated code in your question rather than a new answer. Somebody might get confused.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜