Ruby on rails 通过父资源创建子资源';s索引表-RubyonRails
嗨,我想在资源的索引表中放置一个链接来创建子资源。 我得到了一笔交易和一次手术:Ruby on rails 通过父资源创建子资源';s索引表-RubyonRails,ruby-on-rails,ruby,Ruby On Rails,Ruby,嗨,我想在资源的索引表中放置一个链接来创建子资源。 我得到了一笔交易和一次手术: class Sale < ApplicationRecord belongs_to :user has_one :operation, dependent: :destroy end class Operation < ApplicationRecord belongs_to :sale end 类销售
class Sale < ApplicationRecord
belongs_to :user
has_one :operation, dependent: :destroy
end
class Operation < ApplicationRecord
belongs_to :sale
end
类销售
我希望能够通过销售索引表创建一个操作。
问题是,我需要在点击按钮/链接时创建它,而不是转移到新的操作视图。(操作只有sale_id和id作为属性)
诸如此类
<table>
<tr>
<th>Sale Id</th>
</tr>
<% @sales.each do |sale| %>
<td><%= sale.id %></td>
<td><%= link_to 'Show', sale_path(sale) %></td>
<td><%= link_to 'Edit', edit_sale_path(sale) %></td>
<td><%= link_to 'Delete', sale,
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<td> <%= form_for (@operation) do |o| %>
<%= o.submit 'Create Operation'%>
<% end %>
</td>
</tr>
<% end %>
</table>
销售Id
但我得到了一个错误:“表单中的第一个参数不能包含nil或为空”
我也试过:
<td>
<%= fields_for :operation, @sales.operation do |o| %>
<%= o.submit "Create Operation" %>
<% end %>
</td>
我得到了这个:
未定义的销售“操作”方法::ActiveRecord_关系:0xb1a4ece4>
我也试过:
<td>
<%= link_to 'Create Operation', 'operations#create' %>
</td>
但它将我发送到操作索引视图,而不创建操作
表单中的第一个参数不能包含nil或为空
该错误表示@操作
在表单中为nil
。您应该在sales#index
方法中定义@operation
,因为表单位于sales/index.html.erb
def index
@operation = Operation.new
end
我需要在点击按钮/链接时创建它,而不是
转移到新的操作视图
如果您的意思是,不应该在按钮之后重定向到另一个视图,那么您必须使用AJAX。我建议您看看这些,以了解如何使用AJAX您会遇到什么错误?我刚刚用错误消息编辑了我的问题。成功了!非常感谢。