2017-09-07 18 views
0

ユーザとGeoSceneを多対多の関係でモデル化する必要があります。has_and_belongs_to_many :users/:geo_scenesです。ユーザーフォームでは、geo_scenesにアクセスするための権限をユーザーに割り当てることができます。多対多結合テーブルに余分な属性を追加

--- First User --- 

Geo Scene One [ ] 
Geo Scene Two [x] 
Geo Scene Three [ ] 

現在の形式::

= form_for(@user) do |form| 
... 
    = hidden_field_tag("user[geo_scene_ids][]", nil) 
    - GeoScene.all.each do |s| 
     .checkbox 
     %label 
      = check_box_tag("user[geo_scene_ids][]", s.id, s.id.in?(@user.geo_scenes.collect(&:id))) 
      = s.name 

コントローラが強いのparamsを取ります

各テーブル geo_scenes_usersがフォームを送信した後に作成された結合にgeo_scene記録を確認するために - すべてのgeo_scenesは、チェックボックスでリストされています
def user_params 
    params.require(:user).permit(:email, :password, :password_confirmation, { geo_scene_ids:[] }) 
    end 

今の質問:

方法CA n結合テーブル内の余分なブール値属性writeを操作します。各GeoSceneに2番目のチェックボックスがあり、アップデートが可能です。write geo_scenes_usersのサンプル行は、次のようになります。

user_id | geo_scene_id | write 
------------------------------ 
1  | 1   | true 

私はhas_and_belongs_to_manyショートカットを削除し、余分な参加モデルを構築する必要があると思います。しかし、どのようにしてフォームのチェックボックスリストを管理するのですか?

--- First User --- 

Geo Scene  read write 
--------------------------- 
Geo Scene One [x] [ ] 
Geo Scene Two [x] [x] 
Geo Scene Three [ ] [ ] 

答えて

0

フォームは変更されません。結合モデルと結合を追加するだけです。 collection_singular_ids=(ids)方法(geo_scene_ids=(ids)ご使用の場合)はhas_and_belongs_to_manyhas_many associationsの両方でご利用いただけます。あなたはhas_and_belongs_to_many

で行ったようにあなたは、あなたがフォームから geo_scene_idsを通過したときに動作します利用可能 User#geo_scene_ids=(ids)方法を、持っているだろうその後

http://guides.rubyonrails.org/association_basics.html#has-many-association-reference

class GeoScenesUser # join model 
    belongs_to :geo_scene 
    belongs_to :user 
end 

class User 
    has_many :geo_scenes_users 
    has_many :geo_scenes, through: :geo_scenes_users 
end 

関連する問題