Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Another basic Rails question:

I have a database table that needs to contain references to exactly two different records of a specific data type.

Hypothetical example: I'm making a video game database. I have a table for "Companies." I want to have exactly one developer and exactly one publisher for each "Videogame" entry.

I know that if I want to have one company, I can just do something like:

script/generate Videogame company:references

But I need to have both companies. I'd rather not use a join table, as there can only be exactly two of the given data type, and I need them to be distinct.

It seems like the answer should be pretty obvious, but I can't find it anywhere on the Internet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
635 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just to tidy things up a bit, in your migration you can now also do:

create_table :videogames do |t|
  t.belongs_to :developer
  t.belongs_to :publisher
end

And since you're calling the keys developer_id and publisher_id, the model should probably be:

belongs_to :developer, :class_name => "Company"
belongs_to :publisher, :class_name => "Company"

It's not a major problem, but I find that as the number of associations with extra arguments get added, the less clear things become, so it's best to stick to the defaults whenever possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...