我正在尝试为我的网站设置一个简单的角色模型。用户可以拥有任意数量的角色。现在我将它设置为注册表单上的隐藏字段。我遇到的问题是,在我的嵌套表单中,角色类型没有被保存。正在角色表中创建一个带有uid的条目,但这是关于它的。相关代码如下。任何帮助,将不胜感激。
== 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
来自我的用户控制器的创建方法......
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
结束
继承人的形式......
<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 %>
答案 0 :(得分:0)
作为@Arpit评论 - 摆脱hidden:user_id标签。它只会混淆属性设置器。
我不认为使用roles.new()
构建多个角色(与roles.build()
相同吗?)会削减它。您需要分解单独的角色参数并一次添加一个。或者你可以像这样一次抓住它们:
selected_roles = Role.find_all_by_id(params[:roles])
@user.roles = selected_roles
这会假设您在表单中使用了角色ID,但您出于某种原因......