【问题标题】:Remove an element from the result of an Active Record query从 Active Record 查询的结果中删除一个元素
【发布时间】:2016-12-03 16:56:27
【问题描述】:

我是 Rails 新手,我对 Active Record 查询的结果有疑问。

我有一个类方法 (this_week),它从我的数据库中返回 3 条食谱记录。我想从查询中删除一条返回的记录(不是数据库),同时保留另外两条记录。

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

【问题讨论】:

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


    【解决方案1】:

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

    <%=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?
    

    【讨论】:

    • 添加上述代码后,出现错误:“/home/gregb/workspace/Sandbox/recipe_box/app/views/line_items/index.html.erb:49: syntax error, unexpected ' (', 期待 ')' ...(link_to 'Remove', @line_items(remove_item: params[:remove_i... ... ^ /home/gregb/workspace/Sandbox/recipe_box/app/views/line_items/index .html.erb:49: 语法错误,意外')',期待keyword_end ...arams[:remove_item].to_i + 1) );@output_buffer.safe_append=' ... ^ "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多