在show动作中,有逻辑要求我定义:
@object.nested_object.new (or @object.nested_object.build or @object.nested_object.create)
但是,是时候用以下内容显示嵌套对象的列表了:
@object.nested_objects.each do |nested_objects|
#display
end
使用@ object.nested_object.new创建的临时嵌套对象有一个额外的行项目。
在显示实际的嵌套对象列表之前,有没有办法强制删除该临时对象?
还是有另一种方法可以完成以下任务:
-creating a temporary nested_object for logic tests
-showing a list of nested_objects
我尝过这样的话:
temp_nested_object = @object.nested_object.new
temp_nested_object.delete
但没有成功。
谢谢你的时间!
更新: 我正在努力实现这个目标:
<% if can? :create, @project.tasks.build %>
从这里: https://github.com/ryanb/cancan/wiki/Nested-Resources 我试图找到其他方法来实现这个目标: https://github.com/ryanb/cancan/issues/608 但似乎我需要在视图中解决它。
答案 0 :(得分:2)
首先,你不应该create
一个临时对象。
如果您按照之前的建议,只需执行以下操作:
@object.nested_objects.select(&:persisted?).each do |nested_objects|
#display
end
这将过滤数据库中的对象(无需删除临时对象,它将在请求结束时消失)。
答案 1 :(得分:1)
一种可能性是将其从集合中删除:
# Remove last object in collection
@object.nested_objects.pop