问题描述
我有一个看似简单的查询.我需要创建一个基于单个模型接受多个记录的视图.在我的例子中,模型是 Project,它有 1 个外键(人)和 2 个字段时间、角色.我需要创建一个视图(表单)来插入 5 个角色.
<%结束%><div class="actions"><%= f.submit %>
我有一个看似简单的查询.我需要创建一个基于单个模型接受多个记录的视图.在我的例子中,模型是 Project,它有 1 个外键(人)和 2 个字段时间、角色.我需要创建一个视图(表单)来插入 5 个角色.
<%结束%><div class="actions"><%= f.submit %>
<%结束%>
我收到一条错误消息:未定义的方法`fields[0][stime]'
我不认为嵌套模型的 railscasts 是我需要的.
我将如何创建这个?
项目模型代码如下:
class 项目 <ActiveRecord::Base归属于:人attr_accessible :role, :stime结尾
新方法的 Projects_Controller 代码如下:
def new@project = Project.new结尾
我看到你正计划建立一些一对多的关系(Product has_many :roles
).
这里有一些建议.
首先看一下accepts_nested_attributes_for 方法.您需要将其添加到您的模型中才能执行批量创建.
其次,fields_for 是什么您需要设计嵌套表单.
我会给你一些批量创建简单Product has_many :line_items
案例的例子:
您所需要的只是在控制器中编写如下内容:
@product.update_attributes params[:product]
和 5 个
line_items
将同时创建.
不要忘记将
association
_attributes
列入白名单(请参阅日志中的 params
以查看它).但我认为,如果您遇到批量分配错误,您无论如何都会这样做:)
希望能帮到你.
I have what seems like a simple query. I need to create a view that will accept multiple records based on a single model. In my case the model is Project, which has 1 foreign key (person) and 2 fields time, role. I need to create a view (form) to insert 5 roles.
<%= form_for(@project) do |f| %>
<% 5.times do |index|%>
<div class="field">
<%= f.label :position %><br />
<%= f.text_field "fields[#{index}][stime]" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I get an error message: undefined method `fields[0][stime]'
I do not think the railscasts for nested models is what I need.
How would I go about creating this?
EDIT: The Project model code is below:
class Project < ActiveRecord::Base
belongs_to :person
attr_accessible :role, :stime
end
The Projects_Controller code for the new method is below:
def new
@project = Project.new
end
解决方案
I see you're planning to make some 1-to-many relationship (
Product has_many :roles
).
Here's some advices.
First, take a look at the accepts_nested_attributes_for method. You need to add it to your model to be able to perform mass-create.
Second, fields_for is what you need to design nested forms.
I'll give you some example of mass-creating for a simple
Product has_many :line_items
case:
<%= form_for @product do |f| %>
<%= f.fields_for :line_items, [LineItem.new]*5 do |li_fields| %>
<%= li_fields.text_field :quantity %>
<%= li_fields.text_field :price %>
<br>
<% end %>
<%= f.submit "Create line items" %>
<% end %>
All you need is to write in you controller something like:
@product.update_attributes params[:product]
and 5
line_items
will be created at once.
Don't forget to white-list
association
_attributes
(see params
in your logs to see it). But I think if you get the mass-assignment error you'll do it anyway :)
I hope it helps.
这篇关于Rails 3 - 创建视图以插入多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
07-17 18:45