开发者

Duplicate form fields when using fields_for

I am trying to create a nested form to handle a has_many :through relationship and getting duplicated fields being rendere开发者_运维百科d.

Models

Company

has_many :provides
has_many :services, :through => :provides
accepts_nested_attributes_for :services, :provides
attr_accessible :service_ids

Provide

belongs_to :company
belongs_to :service

Service

has_many :provides
has_many :companies, :through => :provides
has_many :portfolio_items
acts_as_nested_set

Controller

Settings/Services

def index
  @company_services = @company.services
  @service_list = Service.where("parent_id IS NULL")
end

def show
  @user = current_user

  # Find features for supplier based users
  unless @company.blank?
   @my_sectors = @company.sectors
  end
end

def update

if params[:company].nil?
  @company.service_ids = nil
end
respond_to do |format|
  if @company.update_attributes(params[:company])
    format.html { redirect_to settings_path, :notice => "Services successfully updated" }
  else
    format.html { render :index }
  end
 end
end

Views

Form -

<%= form_for @company, :url => settings_service_path(@company), :method => :put do |f| %>
<div>
<ul>
<% @service_list.each do |item| %>
    <%= f.fields_for :provides do |p|  %>
        <%= p.fields_for :services do |s|  %>
            <%= render :partial => "subs", :locals => {:subs => s, :service => item, :f => f, :p => p } %>
        <% end %>
    <% end %>
<% end %>
</ul>
<%= submit_tag("Update") %>
<% end %>

_subs.html.erb

<li>
<%= check_box_tag :service_ids, service.id, @company.services.include?(service), :name => "company[service_ids][]", :class => "checkbox" %>
<%= label_tag service.id, service.service_name %>

<% unless service.children.blank? %>
    <ul>
        <%= render :partial => "subs", :collection => service.children %>
    </ul>
<% end %>
</li>

I know the fields_for is causing the duplication but I don't know why?

Could anybody clarify?


You need to write,

<% @service_list.each do |item| %>
  <%= f.fields_for :provides do |p| %>
   <%= p.fields_for :services, item do |s| %>

this way fields_for will iterate only for matching service each time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜