在rails应用程序中,我想从用户的编辑页面更新嵌套属性。在控制台中我可以这样做:
foo = User.first.memberships.first
foo.organization_id = 10
foo.save
这将更新组织ID。我想用formtastic的形式做这件事。首先,我的用户模型包括:
accepts_nested_attributes_for :memberships
表格如下:
<%= semantic_form_for [:admin, @resource], role: "form" do |f| %>
<div class="form-group">
<%= f.input :email, label: "Email" %>
<%= f.input :avatar, as: :file, name: "Avatar" %>
<%= f.input :first_name, label: "First Name" %>
<%= f.input :last_name, label: "Last Name" %>
<%= f.input :admin, as: :boolean, label: "Admin" %>
<%= f.input :password, as: :password, label: "Password" %>
<%= f.input :password_confirmation, as: :password, label: "Password Confirmation" %>
</div>
<div class="form-group">
<%= f.inputs :for => :memberships do |input| %>
<%= f.input :organizations, :as => :radio, :collection => memberships_for_user %>
<% end %>
</div>
<div class="small-spacer"></div>
<%= f.submit "Save User", class: "btn primary" %>
<% end %>
集合的帮助方法是:
def memberships_for_user
Organization.all
.sort_by { |o| o.name }
.map { |o| [o.name, o.id] }
end
随后的嵌套属性的html如下所示:
<li class="choice">
<label for="user_organization_ids_10">
<input id="user_organization_ids_10" name="user[organization_ids]" type="radio" value="10" />Beer-Davis
</label>
</li>
如何解决此问题,以便此表单更新成员资格加入模型上的organizaiton_id?
答案 0 :(得分:0)
尝试
<%= f.inputs :for => :memberships do |mf| %>
<%= mf.input :organizations, :as => :radio, :collection => memberships_for_user %>
<% end %>