开发者

Unsure about how to use rails 3 check_box

I have a User form as follows, with a checkbox to set the user as admin:

   <%= form_for @user do |f| %>
      <%= render 'shared/error_messages', :object => f.object %>
      <div class="field">
        <%= f.label :name %><br />
        <%= f.text_field :name %>
      </div>
      <div class="field">
        <%= f.label :email %><br />
        <%= f.text_field :email %>
      </div>
      <div class="field">
        <%= f.label :password %><br />
        <%= f.password_field :password %>
      </div>
      <div class="field">
        <%= f.label :password_confirmation, "Confirmation" %><br />
        <%= f.password_field :password_confirmation %>
      </div>
        <%= hidden_field_tag :group_id, @group.id %>
      **<div class="field">
        <%= f.check_box :admin %> 
      </div>**
      <div class="actions">
        <%= f.submit "Sign up" %>
      </div>
    <% end %>

My Users table is as follows

create_table "users", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "email"
    t.string   "encrypted_password"
    t.string   "salt"
    t.boolean  "admin",              :default => false
    t.integer  "group_id"
end

And my User create action is as follows in my Users Controller

def create
    @group = Group.find(params[:group_id])    
    @user = @group.users.build(params[:user])
    if @user.save
      flash[:success] = "You have created a new user"
      redirect_to groups_path
    else
      @title = "Sign up"
      render 'new'
    end
end 

But when I test user.admin for true, it doesn't show as true

<% @users.each do |user| %>
   <li>
     <%if user.admin == true %>
       <%= link_to user.name, user %>
     <% end%>
   </li>
<% end %>

The form works fine otherwise, only the check_box doesn't set t开发者_StackOverflow社区he user.admin to true. Have I missed a key step somewhere? thanks


Are you sure the value is getting set to true in the database? Check it out using dbconsole:

rails dbsconsole

If not, then you may need to make sure it's accessible in your User model:

attr_accessible :admin

Also, as a side note boolean values come with a bonus question mark method in ActiveRecord, so you could do this instead:

if user.admin?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜