Rails link from one model to another based on db field?

Posted by Danny McClelland on Stack Overflow See other posts from Stack Overflow or by Danny McClelland
Published on 2010-05-21T08:02:17Z Indexed on 2010/05/21 8:10 UTC
Read the original article Hit count: 272

Filed under:
|
|
|

Hi Everyone,

I have a company model and a person model with the following relationships:

class Company < ActiveRecord::Base
  has_many :kases
  has_many :people
  def to_s; companyname; end
end

class Person < ActiveRecord::Base
  has_many :kases # foreign key in join table
  belongs_to :company
end

In the create action for the person, I have a select box with a list of the companies, which assigns a company_id to that person's record:

<%= f.select :company_id, Company.all.collect {|m| [m.companyname, m.id]} %>

In the show view for the person I can list the company name as follows:

<%=h @person.company.companyname %>

What I am trying to work out, is how do I make that a link to the company record?

I have tried:

<%= link_to @person.company.companyname %>

but that just outputs the company name inside a href tag but links to the current page.

Thanks,

Danny

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about hyperlinks