【问题标题】:Rails: How to set the grandparent value (association) in ActiveRecordRails:如何在 ActiveRecord 中设置祖父母值(关联)
【发布时间】: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_forsimple_fields_for

如果您能告诉我如何在event.rb 中获取schedule.departure_date,我们将不胜感激。

【问题讨论】:

  • 我认为这是一个错字,您应该使用 Schedule 而不是 schedule

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord


【解决方案1】:
【解决方案2】:

这里有一个关于类似问题的讨论:我认为第二个答案可能对你有用。 belongs_to through associations

回答者建议使用委托来解决。

【讨论】:

  • 感谢您的回答,@Albin。我可以在event.rb 中使用has_one :schedule, through: :room 设置数据。
猜你喜欢
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
相关资源
最近更新 更多