gpt4 book ai didi

ruby-on-rails - 使用 fields_for 时重复表单字段

转载 作者:行者123 更新时间:2023-12-04 19:58:56 26 4
gpt4 key购买 nike

我正在尝试创建一个嵌套表单来处理 has_many :through 关系并获取正在呈现的重复字段。

型号

公司

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

提供
belongs_to :company
belongs_to :service

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

Controller

设置/服务
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

浏览次数

形式 -
<%= 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>

我知道 fields_for 导致重复,但我不知道为什么?

有人能澄清一下吗?

最佳答案

你需要写,

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

这样 fields_for 每次只会迭代匹配服务。

关于ruby-on-rails - 使用 fields_for 时重复表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com