0

概念的な助けが必要です:
ユーザーが本質的にビジネスであると仮定します。従業員がいて、スタッフの役職があります。基本的に、1 人の従業員が複数の役職に就くことができ、1 つの役職に複数の従業員が所属することができます。
私の have_many :through は、結合テーブル スタッフ化を介して従業員とポジションの間で機能しています。ただし、従業員の編集フォームは、この特定のユーザーの位置だけでなく、アプリ全体のチェックボックスとしてすべての位置を返しています。また、更新を送信しても何も保存されません。アソシエーションで何か違うことをする必要がありますか、それともフォーム内のデータを絞り込むためのより良い方法はありますか?
私のモデル:

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

私の従業員コントローラーの更新定義により、 have_many :through 関連付けの行が追加されました。ここで、現在サインインしているユーザーの従業員と役職に絞り込む必要がありますか?

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

3 に答える 3

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
于 2011-09-04T15:44:55.307 に答える
1

returning ALL the positions as checkboxes is exactly what you'd want, no? what if a employee changes positions? you'd need that checkbox then, not only the checked ones..

于 2011-09-02T00:10:13.393 に答える
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
于 2011-09-04T15:18:42.877 に答える