0
在Rails應用程序中,我想更新用戶編輯頁面的嵌套屬性。在控制檯中,我可以這樣做:使用Formtastic 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 %>
爲集合的helper方法是這樣的:
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>
如何解決此問題,以便此表單更新Membersa連接模型上的organizaiton_id?