2016-11-25 47 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)' –