Thought this would be a little straightforward, I may be missing something very simple. I wanted a dropdown list on the teams/create view that let me select the appropriate division for a team, the id of which would be placed in the division_id column in the teams table.
I have two models:
class Team < ActiveRecord::Base
attr_accessible :city, :name
belongs_to :divison
has_many :players
end
class Division < ActiveRecord::Base
attr_accessible :name
has_many :teams
end
and their attendant migrations:
create_table :divisions do |t|
t.string :name
t.timestamps
end
create_table :teams do |t|
t.string :name
t.string :city
t.integer :division_id
t.timestamps
end
On the view, the dropdown list works as expected:
<%= collection_select(:team, :division_id, Division.all, :id, :name) %>
However, when I submit the form, the value is not placed in :division_id. Instead, I get a Can't mass-assign protected attributes: division_id error. From the searching I’ve done, I could remove attr_accessible, but that would present a security flaw.
You can modify your
attr_accessiblein yourTeammodel:I imagine in your
TeamControllercreateaction you are simply callingTeam.new(params[:team]), which is doing a mass-assignment of attributes. For every attribute you want to support for mass-assignment, you need to declare it in yourattr_accessible.