2016-07-29 40 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 ='... ^「 –