Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 3多级连接_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails Rails 3多级连接

Ruby on rails Rails 3多级连接,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我一直在阅读,以了解实现以下目标的最佳Rails 3方法。我将非常感谢建议的方法。(范围?) 我有以下型号: class DonorCategory < ActiveRecord::Base has_many :donors end class Donor < ActiveRecord::Base has_many :donations belongs_to :donor_category end class Donation < ActiveRecord::B

我一直在阅读,以了解实现以下目标的最佳Rails 3方法。我将非常感谢建议的方法。(范围?)

我有以下型号:

class DonorCategory < ActiveRecord::Base
  has_many :donors
end

class Donor < ActiveRecord::Base
  has_many :donations
  belongs_to :donor_category
end

class Donation < ActiveRecord::Base
  belongs_to :donor
end
类DonorCategory 我需要的是: 在给定日期,与给定捐赠者类别关联的所有捐赠 日期标准适用于捐赠,但捐赠者类别标准适用于捐赠者
因此,似乎我需要筛选应用于捐赠查询的捐赠者。

您可以向捐赠者添加一个有用的查询方法。添加一个
有很多。。。通过捐赠类别上的
,您可以轻松访问给定类别的捐赠,自动加入表格,如下所示:

class DonationCategory < ActiveRecord::Base
    has_many :donors
    has_many :donations, through: :donors
end

class Donation < ActiveRecord::Base

  def self.within_dates(start_date, end_date)
    where "created_at >= ? AND created_at <= ?", start_date, end_date
  end

end

# Query looks like this:
some_category.donations.within_dates(start_date, end_date)

# Or this:
DonorCategory.find(123).donations.within_dates(start_date, end_date)

我想你需要的是这样的东西:

class DonationCategory < ActiveRecord::Base
    has_many :donors
    has_many :donations, through: :donors
end

class Donation < ActiveRecord::Base

  def self.within_dates(start_date, end_date)
    where "created_at >= ? AND created_at <= ?", start_date, end_date
  end

end

# Query looks like this:
some_category.donations.within_dates(start_date, end_date)

# Or this:
DonorCategory.find(123).donations.within_dates(start_date, end_date)
Donor.where(:Donor\u category=>DonorCategory.find(id)).where(:date=>start\u date..end\u date)

Rob,非常感谢。我尝试了你的建议:类捐赠:销毁def self。对于捐赠者类别(id),其中捐赠者类别(id):id end end end~我收到一个错误“未知列:捐赠。捐赠者类别(id)”。不知何故,我似乎没有很好地定义类方法。对不起,我做了一个调整。见上图。罗布,非常感谢!你调整过的方法非常有效,它也教会了我很多。也要感谢“RFC1337”的一行回答。我使用了Rob的方法,但我将在其他地方将其他方法合并到应用程序中。非常感谢你们两位抽出时间。不知何故,通过这种格式编辑,失去了一个非常好的回复。我仍然得到一个错误。添加的关系不太正常。我喜欢您的
where
中的日期范围。我不知道这是允许的。整洁。
DonorCategory.find(id)
将执行额外的查询。最好改成:
:捐赠者\类别\ id=>id
。此查询返回捐赠者,但问题表明应返还捐赠,因此您必须首先添加
。捐赠
。@Misha-是的,我知道这会导致额外的查询,导致N+1情况。在这种情况下,您可以添加对includes(:provider_category)的调用,以防止N+1。在这种情况下,只会发生两个查询。