开发者

Rails, has_many list of checkboxes--form field name?

I've got a user model object, assume

class User < ActiveRecord::Base
  has_many :permissions
end

and

class Permission > ActiveRecord::Base
  att开发者_JAVA百科r_accessible :user_id, :permission_name

Obviously there's an id on the table but we really have no interest in that column. The real primary key is user_id + permission_name. The default foreign_key is :user_id

We're trying to generate checkboxes for each permission and can't do it in a loop...

Can someone explain either how rails generates a checkbox name for:

 user.permissions where permission.permission_name == "some string"

or how we might call the check_box_tag method in the .erb file such that it can render a specific checkbox, say where the permission_name is 'ted'?

I'm getting slightly desperate at this point. I found many examples that assume the primary key is the 'id' field and that I simply want to loop through the list of permissions, but nowhere am I seeing an example minus the looping and not using the id as the primary key.

thanks in advance!

edit: I realize that on a table where there are many permissions for many users the permission_name itself is not valid as the primary key, but for our purposes on the form in the case of a new user the user_id doesn't exist and there can only be one of each type of permission_name for that user...perhaps primary_key isn't even what we care about in this case?


I suppose you are looking for the formtastic gem.

Controller:

@permissions = Permission.where(:permission_name => "ted")

or

@permissions = @user.where(:permission_name => "ted")   

It depends on what you really want.

View (simplified):

<%= semantic_form_for :user, :url => some_path(@user) do |f| %>
  <%= f.input :permissions, :as => :check_boxes, :collection => @permissions %>
  <%= f.commit_button %>
<% end %>

In your model, e.g. user.rb, you need to add:

accepts_nested_attributes_for :projects
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜