Rails数据库关系 [英] Rails database relationships

查看:88
本文介绍了Rails数据库关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想互相交流三个模型.

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

Kase,Person和Company.

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

我已将select字段放在创建新的Kase视图和创建新的Person视图上,如下所示:

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.

我想做的是在kase和show.html.erb个人中显示Company记录的联系人.

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

例如,如果我有一家名为"Acme,Inc."的公司并创建一个名为"Random Case"的新Kase,并在创建新案例页面"Acme,Inc."中选择.从公司下拉菜单中.然后,我想在"Random Case" show.html.erb上同时显示"Acme,Inc."和"Acme,Inc. Mobile"等.

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!

谢谢

丹尼

kases_controller

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

推荐答案

基于您在问题中发布的内容,我认为您的模型关联不完整:

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...

这篇关于Rails数据库关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆