Anders
Anders

Reputation: 2941

Rails 4 - select_tag pass parameter to controller

I have two models, Posts and Teams, when the user creates a Post I want the user to select which team it should belong to. And I want to do it using a select_tag. What I currently have is (I use HAML):

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

In my controller:

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

This gives me the following error:

Couldn't find Team without an ID

Note

I previously used radio buttons to achieve this, it looked like this (and worked):

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

So, how can I achieve the same thing using a select_tag?

Upvotes: 0

Views: 1076

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

I assume team_id is an attribute of post, so when you create a Post record you have all post params wrapped into post hash, something like :post => {:title => 'Some title', :team_id => 1} etc.. so team_id is inside post:

@team = current_user.teams.find(params[:post][:team_id])

Upvotes: 1

Related Questions