我有以下型号:Project
和Task
。我使用嵌套属性如下:
<% form_for @project, :url => consultant_report_path(@project), :html => { :method => :put} do |f| %>
<% f.fields_for :tasks do |builder| %>
<%= render "due_dates_fields", :f => builder %>
<% end %>
<p><%= submit_tag %></p>
<% end %>
我有任务类型。
如何仅针对type='economical'
的任务创建此代码?
答案 0 :(得分:0)
您好,您可以通过多种方式实现这一目标:
过滤对象:
<% f.fields_for :tasks do |builder| %>
<% if builder.object.type == 'economical' %>
<%= render "due_dates_fields", :f => builder %>
<% end %>
<% end %>
指定实例:
<% @project.tasks.each do |task| %>
<% if task.type == 'economical' %>
<% f.fields_for :tasks, task do |builder| %>
<%= render "due_dates_fields", :f => builder %>
<% end %>
<% end %>
<% end %>
或指定要使用的集合:
<% f.fields_for :tasks, @economical_taks do |builder| %>
<%= render "due_dates_fields", :f => builder %>
<% end %>
如果有帮助,请查看Fields_for以获取更多信息。
答案 1 :(得分:0)
您可以将其设为自定义关系
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
has_many :economical_tasks, :class_name => 'Task',
:foreign_key => 'project_id',
:conditions => ['tasks.type = ?', 'economical']
accepts_nested_attributes_for :economical_tasks
end
然后您的表单构建器可能如下所示:
<% f.fields_for :economical_tasks do |builder| %>
<%= render "due_dates_fields", :f => builder %>
<% end %>