我的建议:
创建一个用户表单以设置和之间的User
关联Sublocation
我假设子位置已预先填充?
users_controller.rb
def new
@user = User.new
@sublocations = Sublocation.all
respond_to do |format|
# what ever
end
end
def create
@user = User.new(params[:user])
params[:sublocation_ids].each do |key, value|
@user.affiliations.build(sublocation_id: value)
end
respond_to do |format|
if @user.save
# what ever
else
# what ever
end
end
end
def show
@user = User.find(params[:id])
@affiliations = @user.affiliations
end
def set_default
affiliation = Affiliation.find(params[:affiliation_id])
Affiliation.where(user_id: params[:user_id]).update_all(default: false)
affiliation.toggle!(:default)
redirect_to affiliation.user, notice: "Default sublocation set"
end
用户/_form.html.haml
= form_for @user do |f|
.field
# fields for user attributes
.field
%h1 Sublocations
= f.fields_for "sublocations[]" do
- for sublocation in @sublocations
= label_tag sublocation.name
= check_box_tag "sublocation_ids[#{sublocation.name}]", sublocation.id, @user.sublocations.include?(sublocation)
.actions
= f.submit 'Save'
然后也许在用户展示页面上,列出他们所有的子位置并为他们创建一个表单来设置默认值。
用户/show.html.haml
= form_tag user_set_default_path(@user), method: :put do
%table
%tr
%th Sublocation
%th Default?
- @affiliations.each do |affiliation|
%tr
%td= affiliation.sublocation.name
%td= radio_button_tag :affiliation_id, affiliation.id, affiliation.default? ? {checked: true} : nil
= submit_tag "Set default"
路线.rb
resources :users do
member do
put "set_default"
end
end
希望这有助于或至少让你走上正确的道路。