在has_many中使用f.collection_select:通过关系

时间:2016-08-26 21:46:15

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

让我解释一下我的问题,

我正在尝试做的是显示当前用户所属的团队(我的一个模特)的下拉列表,以允许他选择他想加入锦标赛的哪个团队(另一个模型)。这就是我在想的事情(并且没有这样做):

在所选锦标赛的节目视图中

  <%= form_for @new_team, :url => join_tournament_path do |f| %>
      <%= f.collection_select :team_id, current_user.user_teams, team ids of user teams?, user teams names parameter i guess, include_blank: true %>
      <%= f.submit %>
      <% end %>

在控制器中显示操作

def show
    @tournament = Tournament.find(params[:id])
    @new_team = @tournament.teams_in_tournaments.build
end

我希望表单能够将锦标赛ID以及用户选择的团队的团队ID发送到我的自定义“加入”控制器操作,这样可以保存整个事件。

希望有人可以指出我的解决方案,因为我认为我并不真正理解f.collection_select是如何工作的(并且文档在我的情况下并没有真正的帮助)

(顺便说一句,请原谅我的英语)

编辑:

我的模特和关系:

小组:

class Team < ActiveRecord::Base
  has_many :user_teams
  has_many :users, :through => :user_teams

  has_many :teams_in_tournaments
  has_many :tournaments, :through => :teams_in_tournaments

  belongs_to :team_leader, class_name: "User"
end

用户:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :user_teams
  has_many :teams, :through => :user_teams

end

赛:

class Tournament < ActiveRecord::Base
  has_many :teams_in_tournaments
  has_many :teams, :through => :teams_in_tournaments
  belongs_to :organizer, class_name: "User"
end

UserTeam:

class UserTeam < ActiveRecord::Base
  belongs_to :user
  belongs_to :team
  validates :team_id, :uniqueness => { :scope => :user_id }
end

TeamsInTournament:

class TeamsInTournament < ActiveRecord::Base
  belongs_to :tournament
  belongs_to :team
  validates :team_id, :uniqueness => { :scope => :tournament_id }
end

1 个答案:

答案 0 :(得分:0)

你已经到了一半,唯一缺少的是添加你想要在<option>元素中输出的对象的id和名称

在你的情况下,它会是这样的:

 <%= form_for @new_team, :url => join_tournament_path do |f| %>
      <%= f.collection_select :team_id, current_user.user_teams, :id, :name, include_blank: true %>
      <%= f.submit %>
      <% end %>