SamuraiBlue
SamuraiBlue

Reputation: 861

Rails: How to set the grandparent value (association) in ActiveRecord

How can I retrieve the data in the grandparent association.

Give the following models:

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
  ...

I'd like to get schedule.departure_date in event.rb for using callback 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"
  ...

When I try to execute this code, the following error appeared.

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

I use simple_nested_form_for and simple_fields_for in my view.

It would be appreciated if you could give me how to get schedule.departure_date in the event.rb.

Upvotes: 0

Views: 515

Answers (2)

Anurag Verma
Anurag Verma

Reputation: 495

You may try joining the models as shown in this answer Activerecord: find record by grandparent value.

You can also try inverse of option How can I access an ActiveRecord grandparent association through a parent association that has not yet been saved?

Upvotes: 0

Albin
Albin

Reputation: 3032

There is a discussion regarding a similar problem here: I think the second answer might be useful for you. belongs_to through associations

The answerer suggests using delegation to solve it.

Upvotes: 1

Related Questions