Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 避免显式重新加载关联_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 避免显式重新加载关联

Ruby on rails 避免显式重新加载关联,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有以下型号: class Model < ApplicationRecord has_many :states has_one :state, -> { order(created_at: :desc) }, class_name: 'State' def update_state!(state) states.create!(state: state) end end class State < ApplicationRecord belon

我有以下型号:

class Model < ApplicationRecord
  has_many :states
  has_one :state, -> { order(created_at: :desc) }, class_name: 'State'

  def update_state!(state)
    states.create!(state: state)
  end
end

class State < ApplicationRecord
  belongs_to :model
end
一种解决方法是更改
模型的更新状态至:

def update_state!(state)
   states.create!(state: state)
   reload
end
哪种很糟糕

是否仍然可以在不刷新记录的情况下处理此问题?有东西告诉我我错过了什么

在这个场景中,我可能理解Rails可能不知道如何将
:state
:states
关联起来。。。然而,我甚至尝试将
#state
作为一个简单的方法而不是关联,但我仍然面临同样的问题

class Model < ApplicationRecord
  has_many :states
  def state
    states.max_by(&:created_at)
  end

  def update_state!(state)
    states.create!(state: state)
  end
end

class State < ApplicationRecord
  belongs_to :model
end
类模型
我会在模型中添加一个外键列,作为最新记录的“快捷方式”:

class AddStateToModels < ActiveRecord::Migration[6.0]
  change_table :models do |t|
    t.references :state
  end
end

我会在模型中添加一个外键列,作为最新记录的“快捷方式”:

class AddStateToModels < ActiveRecord::Migration[6.0]
  change_table :models do |t|
    t.references :state
  end
end
你退房了吗?你退房了吗?
class Model < ApplicationRecord
  has_many :states, 
    after_add: ->(state){ update_columns(state_id: state.id) }
  belongs_to :state, class_name: 'State'

  def update_state!(state)
    states.create!(state: state)
  end
end
@models = Model.eager_load(:current_state)
               .all