kjs123
kjs123

Reputation: 43

Form Helpers with Ruby on Rails

I'm using a form helper in one of my views and I want the user to choose from a list of options. I then want to store the id equivalent for the option chosen into my database. However, every time I choose an option, its id isn't being stored and the database just says nil for this attribute.

<%= f.label :"Team Against" %><br>
<%= f.select :opposing_team, options_for_select([['Team 1', 1], ['Team 2', 2], ['Team 3', 3]]) %><br>

For example, I have a column in my table called 'opposing_team' and when team 1 is chosen by the user, I want opposing_team to be updated with the value 1. Currently I can choose the range of options in the form but the opposing_team value is always nil.

edit:

def create
    @league = League.find(params[:league_id])
    @team = @league.teams.find(params[:team_id])
    @fixture = @team.fixtures.create(fixture_params)
    if @fixture.save
        redirect_to league_team_path(:league_id => @league.id, :id => @team.id)
    else
        render 'new'
    end

end 
def new
    @team = Team.find(params[:team_id])
    @fixture = Fixture.new 
end

This is what the fixtures controller consists of. The opposing_team is an integer value in the database.

Upvotes: 2

Views: 88

Answers (1)

Matt
Matt

Reputation: 14038

This is a common question, and most often the answer is strong_parameters missing a required key. In your controller do you have a method at the end that looks something like:

def fixture_params
  params.require(:fixture).permit(:value, :other_value)
end

If so, add :opposing_team to the list of keys.

def fixture_params
  params.require(:fixture).permit(:value, :other_value, :opposing_team)
end

Upvotes: 1

Related Questions