質問

私は典型的な多対多の関係を has_many => :through, で、詳細は下記の通りです。

class member
  has_many member_roles
  has_many roles, :through => :member_roles
end

class role
  has_many member_roles
  has_man members, :through => :member_roles
end

class member_role
  belongs_to :member
  belongs_to :role
  # has following fields: member_id, role_id, scope, sport_id
end

どのようにしているうちは、社会の割り当てられる役割です。各役割の範囲は、デフォルトの設定を"すべて"が希望の場合に設定できる"スポーツ".場合、範囲設定のスポーツそのものsport_idできる限りの評価その役割が特定のスポーツ(すなわち、できるだけのチームのスポーツではなく、チームのスポーツ).音は単純であった。

私設私 update_member_roles 行うようになります:

def update

  # Assume we passing a param like: params[:member][:roles]
  # as an array of hashes consisting of :role_id and if set, :sport_id

  roles = (params[:member] ||= {}).delete "roles"
  @member.roles = Role.find_all_by_id(roles.map{|r| r["role_id"]})
  if @member.update_attributes params[:member]
    flash[:notice] = "Roles successfully updated."
    redirect_to member_path(@member)
  else
    render :action => "edit"
  end
end

以上の作品をものに十分で適切なmember_rolesはとてもよく...がんのロールモデルなのMemberRoleモデルの私にはこだわったとしてどのようにアクセスできま接合モデルの設定:範囲:sport_id.

任意のポインタがここにいるのをよろしくお願いいたします。

役に立ちましたか?

解決

あなたは代わりにmember_roles協会のrolesの関連付けを使用する必要があります。

  def update
    # The role hash should contain :role_id, :scope and if set, :sport_id
    roles = ((params[:member] ||= {}).delete "roles") || []
    MemberRole.transaction do 

      # Next line will associate the :sport_id and :scope to member_roles
      # EDIT: Changed the code to flush old roles.
      @member.member_roles = roles.collect{|r| MemberRole.new(r)}

      # Next line will save the member attributes and member_roles in one TX
      if @member.update_attributes params[:member]
        # some code
      else
        # some code
      end
    end
  end

あなたが1つのトランザクションですべてのものを同封してください。

他の可能性はaccepts_nested_attributes_for協会にmember_rolesを使用することです。

他のヒント

音のようにしておくとよいでしょうを入れ子の属性:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top