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>
    
  • 不要将新模板项实际添加到集合中,这从概念角度来看对我更有意义,因为在呈现视图时,实际上不需要将该项与items集合关联,例如:

    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
    

    谢谢我喜欢这个解决方案,因为它将@项从集合中分离出来。谢谢。。。我想我缺少的是执行“查找”检索所有对象,无论是否持久化。理论上,两种解决方案都可行,如果我必须从两种方案中选择一种,我会选择第一种。