I'm relatively new to Rails and I am having an enormous difficulty trying to work with models that have HABTM associations between them.
These are my models:
challenge.rb:
class Challenge < ActiveRecord::Base
has_and_belongs_to_many :skills
attr_accessible :description, :name, :relevant_content, :solutions, :skills
end
skill.rb:
class Skill < ActiveRecord::Base
has_and_belongs_to_many :challenges
attr_accessible :name
end
I've also created a join table called challenges_skills using the following migration:
class CreateChallengesSkills < ActiveRecord::Migration
def up
create_table :challenges_skills, :id => false do |t|
t.integer :challenge_id
t.integer :skill_id
end
end
def down
drop_table :challenges_skills
end
end
And I'm using the helper below to to select my challenge required skills:
<%= collection_select(:challenge, :skills, Skill.all, :id, :name, {}, {:multiple => "true"}) %>
HTML:
<select id="challenge_skills" multiple="multiple" name="challenge[skills][]">
<option value="2">Pesquisa</option>
<option value="3">Senso Critico</option>
<option value="4">Criatividade</option>
<option value="5">Colaboracao</option>
<option value="6">Comunicacao</option>
<option value="7">Proatividade</option>
</select>
Here's my params hash:
{"utf8"=>"✓",
"authenticity_token"=>"n0ggK8eE7vjh+qY33lYbNLJtZW6Sz7LyM2IRVbAPwhM=",
"challenge"=>{"description"=>"My description.",
"skills"=>["", "3", "4"],
"name"=>"Test Challenge",
"relevant_content"=>"My relevant_content",
"solutions"=>"My solutions"},
"commit"=>"Create Challenge!"
}
Error: Skill(#70228688111620) expected, got String(#14953820)
The problem is that I don't know how to handle the skills hash, turn it into an object array inside my challenges controller create action. I know it should be something simple but I cannot find a pratical solution. I want to know how to code to associate the skills collection to my challenge instance inside challenges controller.
ChallengesController#create
def create
@challenge = Challenge.new(params[:challenge])
???
Thanks