- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我的 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
我不确定如何更改我的 Player
和 PlayerPosition
模型以反射(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/
首先,我一直在寻找问题的答案,但找不到。我正在学习 PHP(程序)和 MySQL,目前正在开发足球/足球项目杯。 杯赛的设置与任何正常的欧洲杯赛一样,每支球队进行两回合比赛(主客场),总成绩最好的球队
我是一名优秀的程序员,十分优秀!