Trying to accomplish something similar to Checkbox Adds with HABTM
utilizing a :through association so I can have a model in the middle.
It does not want to play nice.
MODELS
in models/project.rb
has_many :assignments, :dependent => true
has_many :users, :through => :assignments
in models/user.rb
has_many :assignments, :dependent => true
has_many :projects, :through => :assignments
in models/assignment.rb
belongs_to :user
belongs_to :project
VIEW
In views/projects/_form.rhtml:
-
<% User.find(:all, :order => "last_name ASC").each do |g| %>
- <%= check_box_tag 'assignment[user_ids][]', g.id, @project.users.include?(g) %> <%= g.first_name %> <%= g.last_name %> <% end %>
CONTROLLER
in controllers/projects_controller.rb
def update
@project = Project.new(params[:project])
user = User.find(params[“user”].to_i)
assignment = Assignment.new
@project.assignments << assignment
user.assignments << assignment
assignment.save
if @project.update_attributes(params[:project])
flash[:notice] = ‘Project was successfully updated.’
redirect_to :action => ‘show’, :id => @project
raise params.inspect
else
render :action => 'edit'
end
end
The _form renders fine, and on commit i get
ActiveRecord::RecordNotFound in ProjectsController#update
Couldn’t find User with ID=0
RAILS_ROOT: script/…/config/…
Application Trace | Framework Trace | Full Trace
vendor/rails/activerecord/lib/active_record/base.rb:1028:in find_one' vendor/rails/activerecord/lib/active_record/base.rb:1011:in
find_from_ids’
vendor/rails/activerecord/lib/active_record/base.rb:416:in find' app/controllers/projects_controller.rb:71:in
update’
Request
Parameters:
{“commit”=>“Edit”,
“assignment”=>{“user_ids”=>[“3”]},
“project”=>{“duedate(1i)”=>“2006”,
“name”=>“Test Project”,
“duedate(2i)”=>“11”,
“duedate(3i)”=>“20”,
“number”=>“611098”,
“startdate(1i)”=>“2006”,
“startdate(2i)”=>“11”,
“startdate(3i)”=>“18”,
“closed”=>“0”,
“archived”=>“0”,
“description”=>“Some work to do”,
“thisweek”=>“Get it done.”},
“id”=>“2”}
Show session dump
Response
Headers:
{“cookie”=>[],
“Cache-Control”=>“no-cache”}
html | txt
I also tried ‘project[user_ids][]’ in the check_box_tag, but that
renders an error of
undefined method `user_ids=’ for #project:0x32ab9c8
Any thoughts on how I can improve this? Appreciate any feedback.