0

何時間も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

アフィリエーションテーブルには、通常のuser_id列とsublocation_id列があります。'default'という名前のブール列もあります。「新規/ユーザーの編集」フォームでは、チェックボックスを使用して1つ以上のサブロケーションを選択し、サブロケーションを「デフォルト」としてマークする方法を含める必要があります。

繰り返しますが、私は例を次々と読んでいますが、何かが私の脳の中で「クリック」していません。私は必ずしも正確な解決策を探しているわけではありませんが、正しい方向に微調整します。

どうもありがとう、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

users / _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'

次に、おそらくユーザーの表示ページで、すべてのサブロケーションを一覧表示し、デフォルトを設定するためのフォームを作成します。

users / 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 に答える