使用"自"在报关协会(:的has_many,:HAS_ONE) [英] using "self" in association declaration (:has_many, :has_one)

查看:155
本文介绍了使用"自"在报关协会(:的has_many,:HAS_ONE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要参考模型的自我在:的has_many声明。

I need to reference a model's self in a :has_many declaration.

我有一类我们称之为富。富:的has_many吧。美孚有一个名为随机化布尔属性,决定在该酒吧的顺序:的has_many关系。如果随机化是真实的,那么他们是通过有序的RAND()或RANDOM(),这取决于数据库。如果不是这样,它们被标识排序。我有,因为我使用立即加载作出这一声明的关联。我充分意识到,我可以定义foo的方法,返回我想要什么,但我需要的一切加载一次或者400-500查询运行单独=坏。

I have a class we will call Foo. Foo :has_many Bar. Foo has a boolean attribute called randomize that determines the order of the the Bars in the :has_many relationship. If randomize is true, then they are ordered by "RAND()" or "RANDOM()" depending on the DB. If not, they are ordered by id. I HAVE to make this declaration on the association because I am using eager loading. I am well-aware that I can define a method in Foo that returns what I want, but I need to have everything loaded at once or else 400-500 queries are run individually = bad.

class CreateFoo < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.string :name
      t.boolean :randomize, :default => false
    end
  end
end

&NBSP;

 

class CreateBar < ActiveRecord::Migration
  def self.up
    create_table :bars do |t|
      t.string :name
      t.references :foo
    end
  end
end

&NBSP;

 

class Bar < ActiveRecord::Base
  belongs_to :foo
end

&NBSP;

 

class Foo < ActiveRecord::Base
  # this is the line that doesn't work
  has_many :bars, :order => self.randomize ? 'RAND()' : 'id'
end

我如何访问的的性质在的has_many声明?

How do I access properties of self in the has_many declaration?

的事情,失败:

  1. 创建富的方法,它返回正确的字符串
  2. 创建一个lambda函数

这可能吗?

这个问题似乎是,在自我:的has_many的类型是富不:

The problem seems to be that the "self" in :has_many ISN'T of type Foo:

undefined method `randomize' for #<Class:0x1076fbf78>

是我得到的错误之一。需要注意的是它的一般类,而不是Foo对象?为什么?

is one of the errors I get. Note that its a general Class, not a Foo Object... Why??

推荐答案

原来瑞安贝茨谈到一个话题这类似于的此处在Railscast。您需要定义范围的方法之后...

Turns out Ryan Bates has touched on a simliar topic here in a Railscast. You need to define the scope AFTER the method...

这篇关于使用&QUOT;自&QUOT;在报关协会(:的has_many,:HAS_ONE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆