2012-04-11 28 views
0

我已经把一个图来帮助解释问题设置:http://i.imgur.com/ZnN1X.pngHAS_MANY: - 通过Rails 3的一个额外的ID在加盟模式

基本上,我的“新员工”的形式,我目前有一个用于员工姓名的输入字段,以及一个列出所有公司的选择框。如果我选择一家公司,并打出去,它创造了“就业”的新纪录。到现在为止还挺好。

我的问题是,在选择公司时,还需要在“就业”模式中设置类型,该模式链接到“就业类型”模型。理想情况下,我可以有两种不同类型的工作 - 但都列出了相同的公司。

在此先感谢,任何帮助将不胜感激!

回答

1

不知道我完全理解你的问题,但我会对它进行一次尝试。

员工型号:

has_many :employments, :dependent => :destroy 
has_many :companies; :through=>employments 
has_many :employment_types, :through=>employments 

公司型号:

has_many :employments 
has_many :employees; :through=>employments 
has_many :employment_types, :through=>employments 

就业类型型号:

has_many :employments 
has_many :companies; :through=>employments 
has_many :employees; :through=>employments 

就业型号:

belongs_to :employee 
belongs_to :company 
belongs_to :employment_type 

查看代码:

<%= form_for @employee do |f| %> 
    <%= f.text_field :name %> 
    <% 2.times do %> 
    <%= f.fields_for :employments, @employee.employments.build do |employment_fields| %> 
     <%= f.select :company_id, options_from_collection_for_select(Company.all, 'id', 'name') %> 
     <%= f.select :employment_type_id, options_from_collection_for_select(EmploymentType.all, 'id', 'name') %> 
    <% end %> 
    <% end %> 
<% end %> 

在你的图你有ID字段非标准(MODEL_ID),轨道通常更喜欢这些仅仅是ID。但是你可以在加入这每个模型骑默认的主键:

set_primary_key <symbol representing primary key> 
+0

感谢您的帮助,我设置我的关系,因为你描述的,因为它的主要工作 - 虽然当我提交表单,它将在“就业”而不是1中创建2条新记录。一条既有员工ID又有公司ID,另一条有员工ID和雇佣类型ID。有没有办法将这3个记录保存在同一个新记录中? – Kobius 2012-04-11 16:43:42

+1

您可以将代码发布到您的创建方法以及请求中的参数散列副本吗? – 2012-04-11 16:48:52

+0

我没有改变默认的创建方法: – Kobius 2012-04-11 16:55:10