In a rails application I want to update a nested attribute from a user's edit page. In the console I can do this:
foo = User.first.memberships.first
foo.organization_id = 10
foo.save
This will update the organization ID. I want to do this in a form using formtastic. First, my User model includes:
accepts_nested_attributes_for :memberships
The form looks like this:
<%= 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 %>
The helper method for the collection is this:
def memberships_for_user
Organization.all
.sort_by { |o| o.name }
.map { |o| [o.name, o.id] }
end
The ensuing html for the nested attributes look like this:
<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>
How can i fix this so that this form updates the organizaiton_id on the Memberships join model?
Try
<%= f.inputs :for => :memberships do |mf| %>
<%= mf.input :organizations, :as => :radio, :collection => memberships_for_user %>
<% end %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.