Ruby on rails ActiveRecord查询结果中显示的额外记录
问题是: 我有一个页面,希望在其中显示“项目”列表。我还想在此页面上有一个用于添加其他“项目”的表单 控制器中的“新建”操作如下所示:Ruby on rails ActiveRecord查询结果中显示的额外记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,问题是: 我有一个页面,希望在其中显示“项目”列表。我还想在此页面上有一个用于添加其他“项目”的表单 控制器中的“新建”操作如下所示: def新建 @collection=当前用户.collections.find\u by\u id(参数[:collection\u id]) @item_list=@collection.items @item=@collection.items.new 结束这里的问题是,在构建模板项对象时,您也会将其放入集合中,这不是您想要的 在我看来,有两种可能的修复方
def新建
@collection=当前用户.collections.find\u by\u id(参数[:collection\u id])
@item_list=@collection.items
@item=@collection.items.new
结束
这里的问题是,在构建模板项对象时,您也会将其放入集合中,这不是您想要的
在我看来,有两种可能的修复方法:
<ul>
<% @item_list.reject(&:new?).each do |il| %>
<li>
<%= il.name %>
</li>
<% end %>
</ul>
-
class ItemsController < ApplicationController
before_filter do
@collection = collection.find(params[:collection_id])
@items = @collection.items
end
def index
@item = Item.new
end
def create
@item = @items.new(item_params)
if @item.save
redirect_to collection_items_path
else
render action: :index
end
end
private
def item_params
params.require(:item).permit!
end
end
class ItemsController
希望这是有意义的,并为您工作 这将创建相同的项,但不会将其添加到集合中
def new
@collection = current_user.collections.find_by_id(params[:collection_id])
@item_list = @collection.items
@item = Item.new collection_id: @collection.id
end
谢谢我喜欢这个解决方案,因为它将@项从集合中分离出来。谢谢。。。我想我缺少的是执行“查找”检索所有对象,无论是否持久化。理论上,两种解决方案都可行,如果我必须从两种方案中选择一种,我会选择第一种。