0

在阅读了几个小时的 stackoverflow 和观看 railscasts 之后,我决定发帖。这个问题与这里的许多其他问题非常相似,但我只是不明白。这是我的第一个 has_many_through 关联。

class User < ActiveRecord::Base
...
has_many :affiliations
has_many :sublocations, through: :affiliations
...
end

class Sublocation < ActiveRecord::Base
...
has_many :affiliations
has_many :users, through: :affiliations
...
end

class Affiliations < ActiveRecord::Base
...
belongs_to :user
belongs_to :sublocation
...
end

affiliations 表具有通常的 user_id 和 sublocation_id 列。它还具有名为“默认”的布尔列。在我的“新/编辑用户”表单中,我需要通过复选框选择一个或多个子位置,并且还包括一种将子位置标记为“默认”的方法。

同样,我已经阅读了一个又一个示例,但我的大脑中并没有“点击”。我不一定要寻找一个确切的解决方案,而是朝着正确的方向轻推。

非常感谢,CRS

4

1 回答 1

0

我的建议:

创建一个用户表单以设置和之间的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 

希望这有助于或至少让你走上正确的道路。

于 2012-11-07T09:59:33.187 回答