Tag: scope

为什么控制器方法中定义的实例变量不在相应的部分中可用?

例如,给定一个基本控制器,例如: class PostsController < ApplicationController def index @post = Post.all end 实例变量@post在视图posts/index.html.erb可用,但不在部分posts/_index.html.erb 我的主要问题是:这是为什么? 如何在控制器中为部分定义方法,例如,传递实例变量? 更具体的说明:我问这个是因为我在单独的主视图welcome/index.html.erb呈现数据的方式是通过这个post部分。 我已经通过posts/_index.html.erb partial中的Post.all直接调用模型来解决这个限制,但据我所知,这忽略了MVC架构并严重限制我开发更复杂的方法,除非我真的打破约定并将它们写入视图(我认为它可能有用,但设计很差)。 目前,@ post将nil传递给部分符号:welcome / index.html.erb中的post 很明显我错过了什么,所以任何见解都会非常感激! 谢谢 相关文件: views/ posts/ _index.html.erb _new.html.erb show.html.erb welcome/ index.html.erb controllers/ posts_controller.rb welcome_controller.rb 文章/ _index.html.erb 文章/ _new.html.erb 文章/ show.html.erb welcome / index.html.erb相关部分(部分) 控制器/ posts_controller.rb class PostsController < ApplicationController def new end def create @post […]

ActiveRecord通过针对STI类的作用域构建错误类的实例

我希望能够通过其STI类型在一个以某类模型为目标的作用域上调用build方法,并让ActiveRecord构建一个正确类的实例。 class LineItem < ActiveRecord::Base scope :discount, where(type: 'DiscountLineItem') end class DiscountLineItem LineItem.discount.build # Expect an instance of DiscountLineItem here => # 在这里,我期待一个DiscountLineItem的实例,而不是LineItem一个实例。

通过模块共享范围?

我想通过将共享范围移动到模块中来干掉几个模型,例如: module CommonScopes extend ActiveSupport::Concern module ClassMethods scope :ordered_for_display, order(“#{self.to_s.tableize}.rank asc”) end end 我还想创建测试模块的共享规范。 不幸的是,当我尝试在模型中包含共享范围时,我得到: undefined method `order’ for CommonScopes::ClassMethods:Module 有任何想法吗? 谢谢!

Ruby / Rails – 我可以使用连接表的范围(或类方法)作为WHERE子句的一部分吗?

我想抓住包含可购买products所有类别。 class Product true) end class Category < ActiveRecord::Base has_many :products scope :with_purchaseable_products, ????? end 所以,我正在尝试定义:with_purchaseable_products 。 这有效: scope :with_purchaseable_products, joins(:products).where(“products.available is true”).group(:id).having(‘count(products.id) > 0’) 但那不是很干。 有没有办法将我的:purchaseable范围应用于我的:with_purchaseable_products范围? 谢谢。

Rails 4 – Pundit,Scopes:入门

在过去2年多的努力中,我真的在努力学习如何使用专家。 我正在尝试编写范围策略,以便不同的用户可以根据他们适合的范围类接收对象。 我之前曾就同一主题提出了几个问题,但我没有接近解决方案。 我最近的问题是: 这里 , 这里 , 这里 , 这里 , 这里和这里 。 还有其他几个,但这些给出了一般情况,我正在努力解决如何开始的基本原理。 我有一百万个入门问题,并意识到经过4年的尝试(每天–10多个小时),我在尝试学习编码方面并没有真正走得太远,但我面临的当前问题是这个错误: wrong number of arguments (given 2, expected 0) 它指向我将授权@eoi行放在我的控制器中的任何地方。 我之前在这里询问过这个错误 我最初放入set_eoi方法如下: def set_eoi @eoi = Eoi.find(params[:id]) authorize @eoi end 我在控制器中的before操作中使用了该方法: before_action :set_eoi, only: [:show, :edit, :update, :destroy] 当我找到这篇文章的答案时,我停止了这样做, 该post说在之前的行动中不使用授权(即使权威的Go Railsvideo教程显示这样做)。 然后,我将授权调用移动到show动作本身: def show authorize @eoi end 这会产生与在before操作中使用它相同的错误。 请有人帮助您入门。 我目前的设置如下: […]

有没有办法从Ruby中的实例调用私有Class方法?

除了self.class.send :method, args…当然。 我想在类和实例级别提供一个相当复杂的方法,而不需要复制代码。 更新: @Jonathan Branam:这是我的假设,但我想确保没有其他人找到方法。 Ruby中的可见性与Java中的可见性非常不同。 你也很正确, private不能在类方法上工作,尽管这会声明一个私有类方法: class Foo class < NoMethodError: private method ‘bar’ called for Foo:Class