从Active Record查询的结果中删除元素

时间:2016-07-29 05:13:08

标签: arrays activerecord sqlite routes ruby-on-rails-4.2

我是Rails的新手,我遇到了Active Record查询结果的问题。

我有一个Class方法(this_week),它从我的数据库中返回3个食谱记录。我想从查询中删除其中一条返回的记录(数据库),同时保留其他2条记录。

当我在我的视图索引页面中,并尝试删除其中一条返回的记录时,我收到以下错误:“路由错误没有路由匹配[GET]”/ Lomo%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

1 个答案:

答案 0 :(得分: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?
相关问题