Rails database relationships

2019-08-29 18:00发布

I have three models that I want to interact with each other.

Kase, Person and and Company.

I have (I think) setup the relationships correctly:

class Kase < ActiveRecord::Base
#HAS ONE COMPANY
has_one :company

#HAS MANY PERSONS
has_many :persons


class Person < ActiveRecord::Base
belongs_to :company

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

I have put the select field on the create new Kase view, and the create new Person view as follows:

<li>Company<span><%= f.select :company_id, Company.all %> </span></li>

All of the above successfully shows a drop down menu dynamically populated with the company names within Companies.

What I am trying to do is display the contact of the Company record within the kase and person show.html.erb.

For example, If I have a company called "Acme, Inc." and create a new Kase called "Random Case" and choose within the create new case page "Acme, Inc." from the companies drop down menu. I would then want to display "Acme, Inc" along with "Acme, Inc. Mobile" etc. on the "Random Case" show.html.erb.

I hope this makes sense to somebody!

Thanks,

Danny

EDIT: kases_controller

def show
@kase = Kase.find(params[:id])

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @kase }
  format.pdf { render :layout => false }

  prawnto :prawn => { 
             :background => "#{RAILS_ROOT}/public/images/jobsheet.png",

             :left_margin => 0, 
             :right_margin => 0, 
             :top_margin => 0, 
             :bottom_margin => 0, 
             :page_size => 'A4' }
end   end

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-29 18:33

I think your model associations are incomplete based on what you've posted in your question:

class Kase < ActiveRecord::Base
  has_one :company
  has_many :people # Rails should handle the correct plural here
end

class Company < ActiveRecord::Base
  has_many :people
  belongs_to :kase
end

class Person < ActiveRecord::Base
  belongs_to :company
  belongs_to :kase
end

With the assocations set up correctly, you can then access a company's attributes for a given case:

kase.company.name
kase.company.mobile

—or for a given person:

person.company.name
person.company.mobile

You can even get to the company via a person's case:

person.kase.company.name # etc...
查看更多
The star\"
3楼-- · 2019-08-29 18:39

If I understand correctly, your show file would contain something like this to show the mobile number:

# in app/views/kases/show.html.erb
<h1><%=h kase.name %></h1>

<h2>Company Information</h2>
<ul>
  <li>Company Name: <%=h kase.company.name %></li>
  <li>Company Mobile: <%=h kase.company.mobile_phone %></li>
</ul>

Give it a go, see if that's all it takes.

查看更多
登录 后发表回答