Hi quick question on Rails belongs_to association.
In an example we have to models Foo & Hah.
class Foo < ActiveRecord::Base
end
class Hah < ActiveRecord::Base
belongs_to :foo
end
Standard stuff. But my questions comes in. How do I create the code for where every record of model Hah has an foo_id but not every record of model Foo is associated with a Hah model in this way.
I.e.
## Table foos ##
id post
1 stuff
2 dancing
3 now
## Table hahs ##
id line a_id
1 fill 2
3 this 3
Thanks for any help
the question is a little bit vague due to the naming of the Foo
and Huh
but here is the best i can answer to this...
as described by the Active Record Documentation
2.1) A
belongs_to
association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
class Order < ActiveRecord::Base
belongs_to :customer
end
2.2) A
has_one
association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
class Supplier < ActiveRecord::Base
has_one :account
end
2.7) Choosing Between
belongs_to
andhas_one
If you want to set up a one-to-one relationship between two models, you'll need to add >belongs_to to one, and has_one to the other. How do you know which is which?The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
class Supplier < ActiveRecord::Base
has_one :account
end
class Account < ActiveRecord::Base
belongs_to :supplier
end
and about having zero or one relation I think the "zero or one" relation you're looking for is the has_one relation. This relation is not mandatory (unless you add a validation to it). also check this question... typically the Account class will look like the following, if every account is required to have a valid supplier
class Account < ActiveRecord::Base
belongs_to :supplier
validates_presence_of :supplier
end