此表单中有三个字段:
employee
project
project
字段project
出现两次,因此我希望在这种情况下创建两条记录。如果我输入值:
employee: John Doe
project: Project_1
project: Project_2
我想在模型中有两条记录:
employee: John Doe; project: Project_1
employee: John Doe; project: Project_2
这是观点:
<%= simple_form_for(@source) do |f| %>
<div class="form-group">
<%= f.label :employee %>
<%= f.text_field :employee, class: "form-control" %>
</div>
<div class="form-group">
<%= f.input :project, class: "form-control" %>
<%= f.input :project, class: "form-control" %>
</div>
<% end %>
以下是应用程序控制器的代码:
def create
@source = Source.new(source_params)
if @source.save
redirect_to @source, notice: 'Source was successfully created.'
else
render action: 'new'
end
end
非常感谢任何帮助。
答案 0 :(得分:0)
在您的控制器中,您应该与两个项目一起构建模型,然后使用表单助手fields_for
,它将呈现两个项目字段
your_controller.rb
class YourController
def your_action_new
@object = YourModel.new
2.times{ @object.projects.build }
end
end
对于视图,我真的不知道simple_form
的行为,但基本上
视图/ your_views / new.html.erb
<!-- blabla -->
<%= f.fields_for :project do |project_f| %>
<div class="project">
<%= project_f.text_field(:name) %>
<%= project_f.text_field(:description) %>
...
</div>
<% end %>
也不要忘记接受嵌套属性
class YourModel
has_many :projects, dependent: :destroy
accept_nested_attributes_for :projects
end
class YourController
def your_model_params
params.require(:your_model).permit(blabla, projects_attributes: [:id, :name, :blabla, ...])
end
end
end