2016-07-29 42 views
0

我是Rails的新手,我对Active Record查询的结果有问题。从活动记录查询的结果中删除元素

我有一个类方法(this_week),从我的数据库返回3个配方记录。我想从查询中删除一个返回的记录(而不是数据库),同时保留其他2条记录。

当我在我的信息查看索引页,并尝试删除时返回我得到以下错误的记录之一:“路由错误没有路由匹配[GET]“/烙馍%20saltado”

如何删除返回查询的这部分

,可以提供将不胜感激任何帮助。

型号

class LineItem < ActiveRecord::Base 

    belongs_to :recipe 
    belongs_to :recipe_collection 

    def self.this_week 
    @line_items = LineItem.order("RANDOM()").limit(3) 
    @line_items.map{ |line_item| line_item.recipe.title } 
    end 

end 

查看

<%= @line_items.this_week[0] %> <%=link_to 'Remove', @line_items.this_week.delete_at(0) %> <br> 

控制器

class LineItemsController < ApplicationController 
    include UserRecipe #Error: Couldn't find recipe with id/off: undefined meth: Set_rec_collect 
    before_action :set_recipe_collection, only: [:create] 
    before_action :set_line_item, only: [:show, :edit, :update, :destroy, :last_eaten] 

    def index 
    @line_items = LineItem.where(nil) 
    @line_items = LineItem.all 
    @line_items.this_week 

    end 

路线

Rails.application.routes.draw do 
    resources :line_items 
    resources :recipe_collections 
    devise_for :users 
    resources :recipes 
    root "recipes#index" 
end 

enter image description here

回答

0

这里是解决方案之一:在你看来 :

<%=link_to 'Remove', @line_items(remove_item: params[:remove_item].to_i + 1) %> 
在你的控制器

@line_items = LineItem.all 
@line_items = @line_items.limit(LineItem.count - params[:remove_item].to_i) if params[:remove_item].present? 
+0

加入上面的代码后,我得到了错误:“/家/ gregb /工作区/沙盒/ recipe_box/app/views/line_items/index.html.erb:49:语法错误,意外的'(',expecting')'...(link_to'删除',@line_items(remove_item:params [:remove_i ... ...^ /home/gregb/workspace/Sandbox/recipe_box/app/views/line_items/index.html.erb:49:sy ntax错误,意外的')',期待keyword_end ... arams [:remove_item] .to_i + 1)); @ output_buffer.safe_append ='... ^“ –