Rails has_many通过形式

时间:2012-11-07 05:01:18

标签: ruby-on-rails forms has-many-through

经过几个小时阅读stackoverflow并观看railscast,我决定发布。问题非常相似,如果与其他许多问题不完全相同,但我只是没有得到它。 这是我的第一个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列。它还有一个名为'default'的布尔列。 在我的“新/编辑用户”表单中,我需要通过复选框选择一个或多个子位置,还包括将子位置标记为“默认”的方法。

同样,我在例子之后阅读了一些例子,但事实并非只是在我脑中“点击”。我不一定在寻找一个确切的解决方案,而是在正确的方向上轻推。

非常感谢, CRS

1 个答案:

答案 0 :(得分:0)

我的建议:

创建用户表单以设置UserSublocation

之间的关联

我假设sublocations已预先填充?

<强> 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"

<强>的routes.rb

resources :users do
  member do
   put "set_default"
  end
end 

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