从has_many关系中获取子属性

时间:2013-11-11 01:24:37

标签: ruby-on-rails

我需要帮助编写查询,以检查某个日期是否发生event

event has_many daysday有一个名为:date的属性我正在尝试访问,但似乎无法访问它。

代码:

class Event < ActiveRecord::Base
  attr_accessible :title, :days_attributes

  has_many :days
  accepts_nested_attributes_for :days

  scope :occurs_on, lambda {|date| where(Day.first.date => date)}
end

class Day < ActiveRecord::Base
  attr_accessible :date, :event_id
  belongs_to :event

  validates :date, presence: true
end

class EventsController < ApplicationController
  def index
    @events = Event.occurs_on(Date.today)
  end
end

在我看来,我可以这样显示日期:<%= event.days.first.date.strftime("%A, %B %e") %>所以我认为这在我的模型中有用,但事实并非如此。我收到undefined method 'to_sym'错误。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果我正确地阅读了您的问题,我认为您希望在您的范围内执行join

class Event < ActiveRecord::Base
  attr_accessible :title, :days_attributes

  has_many :days
  accepts_nested_attributes_for :days

  scope :occurs_on, lambda {|date| joins(:days).where("days.date = ?", date)}
end