2016-11-25 14 views
0

has_many through:selectとnested形式の選択ヘルパーでどのように選択値を取得できますか?Rails 5 - has_many through:アソシエーションとビューで選択

アプリ/モデル/ team.rb

class Team < ApplicationRecord 
    has_many :team_users 
    has_many :users, through: :team_users 
    accepts_nested_attributes_for :team_users, allow_destroy: true, reject_if: proc { |a| a['user_id'].blank? } 
end 

アプリ/モデル/ user.rb

class User < ApplicationRecord 
    has_many :team_users 
    has_many :teams, through: :team_users 
    accepts_nested_attributes_for :team_users, :teams, allow_destroy: true 
end 

アプリ/モデル/ team_user.rb

class TeamUser < ApplicationRecord 
    belongs_to :team 
    belongs_to :user 
    accepts_nested_attributes_for :team, :user, allow_destroy: true 
end 

アプリ/コントローラ/ teams_controller.rb

class TeamsController < ApplicationController 
    before_action :set_team, only: [:show, :edit, :update, :destroy] 
    before_action :set_team_users, only: [:new, :edit] 
    before_action :set_new_team_user, only: [:new, :edit] 
    before_action :set_team_users_collection, only: [:new, :edit] 

    ... 

    # GET /teams/1/edit 
    def edit 
    end 

    ... 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_team 
     @team = Team.find(params[:id]) 
    end 

    def set_team_users 
     @team_users = @team.team_users 
    end 

    def set_new_team_user 
     @new_team_user = @team.team_users.build 
    end 

    def set_team_users_collection 
     @team_users_collection = User.all.collect { |p| [ p.name, p.id ] } 
    end 

    def team_params 
     params.require(:team).permit(
     :name, 
     :parent_id, 
     team_users_attributes: [:_destroy, :id, :user_id] 
    ) 
    end 
end 

アプリ/ビュー/チーム/ _form.html.erb

<%= form_for(@team) do |f| %> 
    ... 
    <% f.fields_for @team_users do |team_user_f| %> 
    <%= team_user_f.select(:user_id, @team_users_collection, { include_blank: true }, class: 'form-control custom-select', style: 'width:auto;') %> 
    <% end %> 
    ... 
<% end %> 

これは、次のエラーを生成します。

undefined method 'user_id' for #<TeamUser::ActiveRecord_Associations_CollectionProxy:0x007f90a13a3f70>

答えて

0

私はあなたがselect方法であなたの引数が間違っていてもよいと考えている。

<%= team_user_f.select(:team_user, :user_id, @team_users_collection, { include_blank: true }, class: 'form-control custom-select', style: 'width:auto;') %> 

これが機能するかどうかを確認

+0

これはエラーを生成します: '間違った引数数(given 5、expected 1..4)' –

関連する問題