gpt4 book ai didi

ruby-on-rails - 橄榄球运动员的 Rails 模型关系

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:50 27 4
gpt4 key购买 nike

我的 rails 4.2.4 项目中有两个模型,我想将它们结合在一起,但我正在努力创建两者之间的正确关系。有问题的域名是橄榄球,所有代码都可以在 https://github.com/rgbycch/rgbycch-rest/tree/rails 找到。 .模型是:

播放器 ( https://github.com/rgbycch/rgbycch-rest/blob/rails/app/models/player.rb )玩家位置 ( https://github.com/rgbycch/rgbycch-rest/blob/rails/app/models/player_position.rb )

我希望能够创建一种关系,使 Player 可以拥有多个偏好的 PlayingPosition。我相信我的数据库结构需要看起来像这样:

create_table :favoured_positions do |t|
t.references :player, index: true, foreign_key: true # fk to player table
t.references :player_position, index: true, foreign_key: true # fk to player_position table
t.integer :num_favs # additional data for a favored playing position

t.timestamps null: false
end

我想我可以像这样生成一个新的 FavoredPosition 模型:

bundle exec bin/rails generate model FavouredPosition player:references player_position:references num_favs:integer

生成的类如下所示:

class FavouredPosition < ActiveRecord::Base
belongs_to :player
belongs_to :player_position
end

我不确定如何更改我的 PlayerPlayerPosition 模型以反射(reflect)这种新关系。以下是否正确:

class Player < ActiveRecord::Base
has_many :favored_positions, :through => :favoured_positions
end

class PlayerPositions < ActiveRecord::Base
has_many :favored_playing_positions, :through => :favoured_positions
end

你能建议我也为这些表中的任何一个添加索引吗?

谢谢,

肖恩

最佳答案

您需要像这样设置关联:

class Player < ActiveRecord::Base
has_many :favoured_positions
has_many :player_positions, through: :favoured_positions
end

class PlayerPosition < ActiveRecord::Base
has_many :favoured_positions
has_many :players, through: :favoured_positions
end

参见:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

关于ruby-on-rails - 橄榄球运动员的 Rails 模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com