开发者

Grouping by attributes within a form_for

I am working on a Rails project that requires preferences for diferent user types depending on which shool. Thus i have these models:

class Preference < ActiveRecord::Base

  belongs_to :school
  belongs_to :privilege
  belongs_to :user_type

end

class Privilege < ActiveRecord::Base

  has_many :preferences

end

So in my view, i wish to edit the preferences for a given school and i wish to separate and order by user type. So for example my finished view would look like this:

    <form accept-charset="UTF-8" action="/preferences/edit" method="post">
        <table>
            <thead>
                    <td>Pivilege</td>
                    <td>Allowed</td>
                </thead>
                <tbody>
                <h2>Student User type</h2>
                <tr>
                    <td>Privilege 1<td>
                    <td>checkbox for privilege 1<td>
                </tr>
<tr>
                    <td>Privilege 2<td>
                    <td>checkbox for privilege 2<td>
                </tr>
                <h2>Employee User type</h2>
                <tr>
                    <td>Privilege 1<td>
                    <td>checkbox for privilege 1<td>
                </tr>
<tr>
                    <td>Privilege 2<td>
                    <td>checkbox for privilege 2<td>
                </tr> 开发者_Python百科              
            </tbody>    
        </table>
    </form>

The problem is i do not know how to itarate within a (form_for @preferences do |f|) block and group this array (@preferences) by user_types.

Can anybody help me? Thanxs in advance


I ended up using nested attributes and verifying if the preference belongs to that user type (although I insist that there should be a more "Rails way" of doing it. Hopes this helps somebody:

<%= form_for @school, :url => {:controller => :preferences, :action => :update, :id => @school.id} do |f| %>
        <h2>Change Preferences</h2>     
    <% UserType.all.each do |ut|%>
         <h3><%= ut.name%></h3>
            <table>

                <thead>
                    <td>Privilege</td>
                    <td>Allowed</td>
                </thead>

                <tbody>

                <%= f.fields_for :preferences do |pref| %>
                  <% if pref.object.user_type == ut%>
                    <tr>
                      <td><%= pref.object.privilege.name%></td>
                      <td><%= pref.check_box :allowed, {:allowed => pref.object.allowed} %></td>
                    </tr>
                  <% end %>
                <% end%>
                </tbody>    

          </table>      
    <% end %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜