If I want to have Model has_one :model2, and Model2 has_one :model, do I have to create join table then? Something like model_model2? And then tables would look like: Model (id) and Model2 (id) and ModelModel2 (id, model_id, model2_id) ?
Asked
Active
Viewed 549 times
1 Answers
1
You just need to create the relation field, tail will have :dog_id
and dog will have :tail_id
Actually you can also create it using only 1 field, for example tail will have :dog_id
and that's all, and then the relation would be
dog has one tail
tail belongs to dog
And that's it.
If you want to try a marriage table in between, you'll need to create a join model DogTail
class DogTail < ActiveRecord::Base
belongs_to :dog
belongs_to :tail
end
Then create a has_one :through
relation
class Dog < ActiveRecord::Base
has_one :tail, through: :dogtail
end
class Tail < ActiveRecord::Base
has_one :dog, through: :dogtail
end

lucascaro
- 16,550
- 4
- 37
- 47

Mohammad AbuShady
- 40,884
- 11
- 78
- 89
-
I know belong_to/has_one relation. To your first sentence: Do you mean add ids and has_one relation to both models? I am asking cause I have been wondering if I can use has_one in two models(not: belong_to/has_on). ;-) just wondering what are the possibilities – zombie_ghast Jan 18 '15 at 22:18
-
I'm not sure if would become an invalid relation or not, but if you want to try it you should add the id fields to both models, then try `has_one` on both, and if it didn't work you can try `belongs_to` on both too. – Mohammad AbuShady Jan 18 '15 at 22:23