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