簡體   English   中英

Rails:如何在ActiveRecord中設置祖父母值(關聯)

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

如何檢索祖父母關聯中的數據。

給出以下模型:

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 ,將event.rb

這里有一個關於類似問題的討論:我認為第二個答案可能對您有用。 通過關聯歸屬

回答者建議使用委托來解決它。

您可以嘗試按此答案Activerecord中所示加入模型:按祖父母值查找記錄

您還可以嘗試選擇選項的inverse of 如何通過尚未保存的父關聯訪問ActiveRecord祖父母關聯?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM