views:

13

answers:

2

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

+1  A: 

The thing is, link_to cannot guess where you want it to lead to, if you give it only the text of the link :)

In order to have the link lead to the company page, you need to add a path:

<%= link_to @person.company.companyname, company_path(@person.company) %>

This assumes you have proper restful routes for your company

map.resources :companies

and the page you're heading to is companies/show.html.erb.

neutrino
Thanks for your in-depth response, I have managed to get this working.
dannymcc
+2  A: 

You need pass in second argument the path where you want go

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

or with the full version :

<%= link_to @person.company.companyname, company_url(@person.company) %>
shingara
Great, I knew I must have been missing something. Thanks!
dannymcc