我正在开发一个Rails项目,该项目需要不同用户类型的首选项,具体取决于哪个shool。因此,我有这些模型:
class Preference < ActiveRecord::Base
belongs_to :school
belongs_to :privilege
belongs_to :user_type
end
class Privilege < ActiveRecord::Base
has_many :preferences
end
所以在我看来,我希望编辑给定学校的偏好,我希望按用户类型分开和排序。例如,我的完成视图将如下所示:
<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>
</tbody>
</table>
</form>
问题是我不知道如何在(form_for @preferences do |f|)
块内进行itarate并按user_types对此数组(@preferences)进行分组。
任何人都可以帮助我吗? Thanxs提前
答案 0 :(得分:0)
我最终使用嵌套属性并验证首选项是否属于该用户类型(尽管我坚持认为应该有更多“Rails方式”)。希望这有助于某人:
<%= 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 %>