I have Match
model and I have Player
model. Now I want to add to Match
two fields like: playerone
and playertwo
. I want to playerone
have a reference to specific Player
object and playertwo
have a reference to another Player
object too.
I was trying something like that:
rails g model Match player:references
but this way I am able to create only one field. And I can't create custom name for this field.
Or I can just create playerone:integer
filed and puts here player's id (in controller). But is it ok?
If you are always going to have only 2 players per match, its fine to create player_one_id:integer and player_two_id:integer fields. In the Match model, you will just have
has_one :player_one, class_name: 'Player', primary_key: :player_one_id
has_one :player_two, class_name: 'Player', primary_key: :player_two_id
You can then just set these from a form
<%= f.collection_select :player_one_id, Players.all, :id, :name %>
<%= f.collection_select :player_two_id, Players.all, :id, :name %>
Or programatically
@match.player_one = Player.find(1)
@match.player_two = Player.find(2)
The model cmdline generator for this model would look something like this
rails g model Match player_one_id:integer:index player_two_id:integer:index
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.