【发布时间】:2016-07-23 23:17:48
【问题描述】:
如何检索祖父关联中的数据。
给出以下模型:
class Schedule < ActiveRecord::Base
belongs_to :user
has_many :rooms
accepts_nested_attributes_for :rooms, allow_destroy: true
...
class Room < ActiveRecord::Base
belongs_to :schedule
has_many :events
accepts_nested_attributes_for :events, allow_destroy: true
...
class Event < ActiveRecord::Base
belongs_to :room
...
我想在 event.rb 中获取 schedule.departure_date 以使用回调 before_save。
event.rb
class Event < ActiveRecord::Base
belongs_to :room
before_save :assign_date
private
def assign_date
self.from = DateTime.new(schedule.departure_date.year, schedule.departure_date.month, schedule.departure_date.day, from.hour, from.min)
end
schema.rb
create_table "schedules", force: :cascade do |t|
t.date "departure_date"
...
create_table "rooms", force: :cascade do |t|
t.integer "schedule_id"
...
create_table "events", force: :cascade do |t|
t.time "from"
t.integer "room_id"
...
当我尝试执行这段代码时,出现以下错误。
development.log
NameError (undefined local variable or method `schedule' for #<Event:0x000000058bdd28>):
app/models/event.rb:15:in `assign_date'
app/controllers/schedules_controller.rb:51:in `update'
schedules_controller.erb
def update
@schedule.room.maximum(:day)
if @schedule.update(schedule_params)
flash[:success] = "Schedule updated!"
redirect_to root_url
else
render 'edit'
end
end
...
private
def schedule_params
params.require(:schedule).permit(:title, :departure_date, rooms_attributes: [:id, :_destroy, :room, :day, events_attributes: [:id, :_destroy, :from, :to, :title, :detail]])
end
在我看来,我使用simple_nested_form_for 和simple_fields_for。
如果您能告诉我如何在event.rb 中获取schedule.departure_date,我们将不胜感激。
【问题讨论】:
-
我认为这是一个错字,您应该使用 Schedule 而不是 schedule
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord