Ruby on rails Ruby Rails ActiveRecord关联,通过“属于”关系拥有一个
模型 我当前可以通过调用Ruby on rails Ruby Rails ActiveRecord关联,通过“属于”关系拥有一个,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,模型 我当前可以通过调用 create_table "game_results", force: :cascade do |t| t.string "result" end create_table "games", force: :cascade do |t| t.integer "game_result_id" end 通过建立正确的协会,我相信我应该能够 @game.game_result.result 我尝试了通过关联进行的多个配置,但均无效,例如: @game.re
create_table "game_results", force: :cascade do |t|
t.string "result"
end
create_table "games", force: :cascade do |t|
t.integer "game_result_id"
end
通过建立正确的协会,我相信我应该能够
@game.game_result.result
我尝试了通过关联进行的多个配置,但均无效,例如:
@game.result
类游戏
如果您能给我一些建议,我将不胜感激。谢谢
class Game < ActiveRecord::Base
belongs_to :game_result
has_one :result, through: :game_result, source: :result
end
根据你的情况,你可能最终不需要允许
从本质上说,这只是一种简写的方式
class Game < ActiveRecord::Base
belongs_to :game_result
delegate :result, to: :game_result, allow_nil: true
end
类游戏
此解决方案非常有效。到目前为止,我还不需要实现allow_nil。基本上,如果一个游戏没有相关的游戏结果,你需要allow_nil。所以,如果你不能有这种情况,那么你永远不会需要它。
class Game < ActiveRecord::Base
belongs_to :game_result
end
class Game < ActiveRecord::Base
belongs_to :game_result
delegate :result, to: :game_result, allow_nil: true
end
class Game < ActiveRecord::Base
belongs_to :game_result
def result
return nil if game_result.nil?
game_result.result
end
end