I’m trying to set up a simple Roles model for my site. Users can have any number of roles. Right now I’m setting it up to be a hidden field on the signup form. The problem I’m running into is that in my nested form the role type isn’t being saved. An entry with the uid is being created in the roles table but that’s about it. The relevant code is below. Any help would be appreciated.
== Schema Information
Table name: roles
id :integer not null, primary key
user_id :integer
role :string(255)
created_at :datetime not null
updated_at :datetime not null
Heres the create method from my users controller…
def create
@user = User.new(params[:user])
if @user.save
@role = @user.roles.new(user_id:@user.id, role:params[:role])
flash[:success] = "Thanks for singing up for the Auditions App, any audition invitations will be visible on this page"
#need to add the role guest to user roles
redirect_to @user
else
render 'new'
end
end
Heres the form….
<div class="span10 offset1 ajax-form">
<%= form_for(@user, :html => {:class => 'well'}) do |f| %>
<h3>Guest Account Signup</h3>
<%= render 'shared/error_messages' %>
<div class="pull-left form-field"><%= f.label :first_name %>
<%= f.text_field :first_name, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :last_name %>
<%= f.text_field :last_name, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :email %>
<%= f.text_field :email, :class => 'span4' %></div>
<div class="pull-left form-field span4"></div>
<div class='clear'></div><!--close .clear-->
<div class="pull-left form-field"><%= f.label :password %>
<%= f.password_field :password, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, :class => 'span4' %></div>
<div class="form_row pull-left form-field">
</div>
<%= f.hidden_field :role, :value => 'guest' %>
<%= f.submit "Create my account", :class => "btn btn-large btn-primary pull-left form-field" %>
<div class='clear'></div><!--close .clear-->
<% end %>
As @Arpit comments – get rid of the hidden :user_id tag. It’s only confounding the attribute setter.
And I don’t think building multiple roles using
roles.new()(is that the same asroles.build()?) is going to cut it. You’ll need to break out the separate roles’ parameters and add them one at a time. Or you can grab them in one go like this:This would assume that you are using role ids in your form, but you aren’t for some reason…