Aydar Omurbekov
Aydar Omurbekov

Reputation: 2117

Update a list of objects in rails 3

I have an array of objects @website_links in the view and want to update them, but when i send to the controller action i get a list of only checked fields, how to get the whole object's list(checked and unchecked)? And how can i properly update them inside update action?

<%= form_tag(:controller => 'website_links', :action => 'update', method: "put") do %>
    <%- @website_links.each do |link| %>
       <%= link.link %> 
       <%=  check_box_tag "checked[]", 1, link.checked"  %>
    <% end %>
    <%= submit_tag "Update" %>
<% end %>

Upvotes: 0

Views: 578

Answers (1)

zwippie
zwippie

Reputation: 15515

You are not using the form and input helpers in combination with an ActiveRecord model. Instead, you are using form helpers that end with _tag to generate a dumb form.

I will assume that website_links is an ActiveRecord model.

To create a smarter form, in this case it may be necessary to take the parent object of all those website_links. This way, all those website links have a common parent to refer to.

In this case lets pretend that there is a model called Website that will act as the parent. This Website has_many :website_links and of course WebsiteLink belongs_to :website.

Let's create a form for the Website model to be rendered when the url website/45/edit is called. Leave the default code that is generated for the update method in the website_controller.

<%= form_for @website do |f| %>
  <%= f.input_field :website_name %>

  <%= f.fields_for :website_links do |subform| %>
    <%= subform.object.link_name %>
    <%= subform.check_box :checked %>
  <% end %>

  <%= f.submit %>
<% end %>

Also, add this line to the Website model:

accepts_nested_attributes_for :website_links, allow_destroy: true

This allows the website model to take parameters for the associated website_links and update those links.

Note that I have not tested this code and it may not suit your needs. Perhaps you need to add and remove links too. Some good explanation can also be found in this RailsCast.

Upvotes: 1

Related Questions