Rails show company name rather than company ID
I am making good progress with my first Rails app with a lot of help from the great community here at Stack Overflow.
I have a basic application that has the following models:
kase person company party
I have associated them in the following way:
class Kase
belongs_to :company # foreign key: company_id
has_and_belongs_to_many :people # foreign key in join table
class Person
has_and_belongs_to_many :kases # foreign key in join table
class Company
has_many :kases
has_many :people
class Party
has_and_belongs_to_many :people
has_and_belongs_to_many :companies
At the moment, if I create a company and then go to create a new case (kase), I can choose from a drop down list the company I want (from the companies database) and then on the show view I can output the name of the chosen company for the case by using this code:
<li>Client Company: <span><%=h @kase.company.companyname %></span></li>
However, if I add a new Person using the same method - I can successfully assign a company to the person, but on the show view it only outputs the company ID number using this code:
<li>Person Company: <span><%=h @person.company.company_id %></spa开发者_StackOverflow中文版n></li>
If I change the above to:
<li>Person Company: <span><%=h @person.company.companyname %></span></li>
I get the following error:
undefined method `company' for #<Person:0x105dc4938>
So it seems I can call the company ID, but nothing else from the company database, any ideas where I am going wrong?
Thanks,
Danny
You have
class Person < ActiveRecord::Base
has_and_belongs_to_many :kases
end
This means that you can do
@person = Person.find(1)
@person.kases.each do |kase|
puts kase.company.name
end
But keep in mind that, in order for @person.company
to work, you would need to have one of the following:
class Person < ActiveRecord::Base
belongs_to :company # option 1
has_one :company # option 2
end
I am not sure why you can even call the company_id like that, are you sure you aren't doing:
<li>Person Company: <span><%=h @person.company_id %></span></li>
I think the problem is that you are missing the reference to Company in your Person model. Try changing your Person model to:
class Person
has_and_belongs_to_many :kases # foreign key in join table
belongs_to :company
This should allow you to do lookups between people and companies in both directions.
not tested, did you try add:
belongs_to :company
in Person model?
精彩评论