hi all,
i have a has_many :through r’ship in my application. my tables are -
users, apps(short form for applications), categorizations. i’m trying to
create a user in new.rhtml where all apps are also shown in checkboxes
for selection. on submit, user gets created but the join table i.e.
categorizations table doesn’t get updated. where am i going wrong?
doesn’t the join table gets updated automatically? or do i’ve to update
it manually? if yes, how? Any help will be greatly appreciated. thanks
in advance.
code:
class App < ActiveRecord::Base
has_many :categorizations
has_many :users, :through => :categorizations
end
class User < ActiveRecord::Base
has_many :categorizations
has_many :apps, :through => :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :user
belongs_to :app
end
class UsersController < ApplicationController
def new
@user = User.new
@apps = App.find(:all)
end
def create
@user = User.new(params[:user])
@user.save!
redirect_to(:action => “new”)
flash[:notice] = “Thanks for signing up!”
rescue ActiveRecord::RecordInvalid
render :action => ‘new’
end
end
users/new.rhtml
<%= error_messages_for :user %>
<% form_for :user, :url => users_path do |f| -%>
Login
<%= f.text_field :login %>
Email
<%= f.text_field :email %>
Password
<%= f.password_field :password %>
Confirm Password
<%= f.password_field :password_confirmation %>
Applications
<%for app in @apps%>
<%= check_box_tag "user[app_ids][]", app.id,
@user.apps.include?(app)%> <%=app.name%>
<%end%>
<%= submit_tag 'Sign up' %>
<% end -%>log:
Parameters: {“user”=>{“password_confirmation”=>“aaaa”, “app_ids”=>[“1”,
“2”, “3”, “4”], “login”=>“aaaa”, “password”=>“aaaa”,
“email”=>“[email protected]”}, “commit”=>“Sign up”, “action”=>“create”,
“controller”=>“users”}