Rails 4 - select_tag将参数传递给控制器

时间:2014-07-16 21:28:34

标签: ruby-on-rails ruby ruby-on-rails-4 html-select

我有两个模型,PostsTeams,当用户创建帖子时我希望用户选择它应属于哪个团队。我想用select_tag来做。我目前拥有的是(我使用HAML):

= f.label :team_id, "Select team"
= select_tag :team_id, options_from_collection_for_select(current_user.teams, :id, :name)

在我的控制器中:

def create

  # I want to pass :team_id here, but I'n not sure how...
  @team = current_user.teams.find post_params[:team_id]
  @post = @team.posts.build post_params
  @post.user = current_user

这给了我以下错误:

Couldn't find Team without an ID

注意

我之前使用单选按钮来实现这一点,它看起来像这样(并且有效):

- current_user.teams.each do |team|
  = f.radio_button 'team_id', team.id
  = team.name

那么,我怎样才能使用select_tag来实现同样的目标?

1 个答案:

答案 0 :(得分:1)

我认为team_idpost的属性,因此当您创建Post记录时,您将所有post params包装成post hash,类似于:post => {:title => 'Some title', :team_id => 1}等。所以{{ 1}}在team_id内:

post