2016-11-25 61 views
0

如何通過has_many獲取選擇幫助器中的選定值:關聯和嵌套形式?Rails 5 - has_many通過:關聯和在視圖中選擇

應用/模型/ 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

這會產生錯誤:錯誤的參數數量(給定5,預期1..4)' –