简体   繁体   中英

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

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

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) %>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM