2016-07-15 3 views
1

ここに私の最初の質問!私のユーザーに「主要企業」を割り当てようとしています。これらは、many-to-manyリッチ結合テーブルにあります。この表には、new,key,activeなどの属性があります。私は長いリストのユーザーに会社を割り当てたいとし、SimpleFormを使ってその会社に割り当てたい。リレーションリレーションアトリビュートに基づくリミットアソシエーション

リッチなリレーションの属性に基づいてアソシエーション関係を除外して制限することを除いて、すべて機能しています。私はユーザーごとに会社の関係を持っていますが、それらのすべてがkey-関係またはnew-関係です。私はアソシエーションがkeyで他のものには触れないようにしたいだけです。これらの会社をユーザーに割り当てるときには、activeという属性をtrueに設定する必要があります。私のコードは次のようになります。

user.rb

class User < ActiveRecord::Base 
    has_many :company_user_relationships 
    has_many :companies, through: :company_user_relationships 

company.rb

class Company < ActiveRecord::Base 
    has_many :company_user_relationships 
    has_many :users, through: :company_user_relationships 

schema.rb

create_table "company_user_relationships", force: true do |t| 
    t.integer "company_id" 
    t.integer "user_id" 
    t.boolean "key" 
    t.boolean "active" 
    t.datetime "last_contacted" 
    t.string "status_comment" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "status" 
    t.boolean "new" 
end 

users_controller.rb

def assign_key_companies 
    User.update(params[:users].keys, params[:users].values) 
    redirect_to(:back) 
end 

ビュー

= form_for :user_companies, 
     url: assign_key_companies_users_path, 
     html: {:method => :put} do |f| 
    - users.each do |user| 
    = simple_fields_for "users[]", user do |u| 
     tr 
     td.col-md-4 
      = "#{user.first_name} #{user.last_name}" 
     td.col-md-8 
      = u.association :companies, label: false, collection: @key_company_candidates, 
         input_html: {data: {placeholder: " Assign key companies"}, class: 'chosen-select'} 
    = submit_tag "Save key companies", class: "btn btn-success pull-right" 

私は基本的にのみ、レコードを更新する際に、常にtruekey -fieldを入れてuser.companies.where(key: true)とSQL COMMITを示したいと思います。

私が望む関連性にのみ影響するようにフィルタリングするにはどうすればよいですか?

答えて

0

私は2つの方法が考えられます。

あなたが条件を指定することができるようにあなたは、それが実際にすべての3つのテーブル間の結合テーブルをやってuser.companies呼び出すと、関連付けレベル

class User < ActiveRecord::Base 
    has_many :company_user_relationships, -> { where("company_user_relationships.key" => true) } 

それとも

user.companies.where("company_user_relationships.key" => true) 

でそれをフィルタリングするためにまず、私の例のように。

+0

ありがとうございました!私はあなたが示した最初の例のように、主要な関係しか示していない別のhas_many関係を追加する方法を見つけました。レールマジックを使って、質量を割り当てたら自動的に私のためのすべてのプロパティを設定します:) – feggak

関連する問題