2011-09-01 98 views
0

我需要一些概念上的帮助:
假设您的用户本质上是一个业务。你有员工,你有员工职位。基本上,一名员工可以持有多个职位,一个职位可以容纳多名员工。
我的have_many:through通过联合表Staffization在员工和职位之间工作。但是,我的员工编辑表单将所有职位作为整个应用程序的复选框返回,而不仅仅是针对此特定用户的复选框。而且,当我提交更新时,没有人正在保存。 我是否需要做一些与我的关联不同的事情,还是有更好的方式来缩小表单中的数据?
我的模型:Rails 3 has_many:通过概念

class User < ActiveRecord::Base 
    has_many :employees, :dependent => :destroy 
    has_many :positions, :dependent => :destroy 

class Employee < ActiveRecord::Base 
    belongs_to :user 
    has_many :positions, :through => :staffizations 
    has_many :staffizations, :dependent => :destroy 

class Position < ActiveRecord::Base 
    belongs_to :user 
    has_many :employees, :through => :staffizations 
    has_many :staffizations, :dependent => :destroy 

class Staffization < ActiveRecord::Base 
    belongs_to :employee 
    belongs_to :position 

我的员工编辑字段的形式设置,返回复选框可能位置的员工可以持有,但在整个应用程序返回的所有位置,而不是更新数据时,我打提交:

- Position.all.each do |position| 
    = check_box_tag :position_ids, position.position_name, @employee.positions.include?(position), :name => 'employee[position_ids][]' 
    = label_tag :position_ids, position.position_name 

我的员工控制器更新DEF增加了行了have_many:通过关联。我是否应该将收益缩小到目前登录的用户员工和职位?

@employee.attributes = {'position_ids' => []}.merge(params[:employee] || {}) 

回答

1

将所有位置作为复选框返回正是你想要的,不是吗? 如果员工更换职位,该怎么办?你需要那个复选框然后,不仅是选中的那个..

+0

感谢您的答复的辅助用这个!......所有该用户的复选框,将是一件好事。但是,应用程序中每个用户的所有复选框都很糟糕。我想知道如果我的问题是在雇员控制器中,我在更新def中添加了上面的行。我不确定是否需要在某处传入当前用户的ID。 –

0

感谢一位朋友,因为我的员工和职位之间的have_many属于业务。我需要将attr_accessible position_ids和attr_accessible employee_ids添加到相应的模型中。此外,在我的员工的视野,我需要添加的选项,让我呼吁职位只要求与该业务有关的职位,像这样:

- Position.find_all_by_user_id(@employee.user_id).each do |position| 
    = check_box_tag :position_ids, position.id, @employee.positions.include?(position), :name => 'employee[position_ids][]' 
    = label_tag :position_ids, position.position_title 
2

首先,你不应该使用:

class Employee 
    has_and_belongs_to_many :positions 
end 

class Position 
    has_and_belongs_to_many :employees 
end 

然后,你可以拉近与可用的位置:

Position.where(:user_id => @employee.user_id).each # etc. 

,你甚至可以使一个范围吧:

class Position 
    def available_for_employee employee 
    where(:user_id => employee.user_id) 
    end 
end 

...然后在生成您的复选框

def position_checkboxes_for_employee employee 
    Position.available_for_employee(employee).each do |position| 
    = check_box_tag :position_ids, position.position_name, @employee.positions.include?(position), :name => 'employee[position_ids][]' 
    = label_tag :position_ids, position.position_name 
    end 
end 
+0

是的,谢谢,那也行得通... has_many通过has_and_belongs_to_many获得的好处是关系的连接表,它允许我在将来添加其他属性。 –