How to create belongs_to connections in some cases, Rails 4 -


hi quick question on rails belongs_to association.

in example have models foo & hah.

    class foo < activerecord::base     end       class hah < activerecord::base        belongs_to :foo     end 

standard stuff. questions comes in. how create code every record of model hah has foo_id but not every record of model foo associated hah model in way.

i.e.

## table foos ##    id     post     1     stuff     2     dancing     3       ## table hahs ##    id     line     a_id     1     fill      2     3          3 

thanks help

the question little bit vague due naming of foo , huh here best can answer this...

as described active record documentation

2.1) belongs_to association sets one-to-one connection model, such each instance of declaring model "belongs to" 1 instance of other model. example, if application includes customers , orders, , each order can assigned 1 customer, you'd declare order model way:

class order < activerecord::base   belongs_to :customer end 

2.2) has_one association sets one-to-one connection model, different semantics (and consequences). association indicates each instance of model contains or possesses 1 instance of model. example, if each supplier in application has 1 account, you'd declare supplier model this:

class supplier < activerecord::base   has_one :account end 

2.7) choosing between belongs_to , has_one if want set one-to-one relationship between 2 models, you'll need add >belongs_to one, , has_one other. how know which?

the distinction in place foreign key (it goes on table class declaring belongs_to association), should give thought actual meaning of data well. has_one relationship says 1 of yours - is, points you. example, makes more sense supplier owns account account owns supplier. suggests correct relationships this:

class supplier < activerecord::base   has_one :account end  class account < activerecord::base   belongs_to :supplier end 

and having 0 or 1 relation think "zero or one" relation you're looking has_one relation. relation not mandatory (unless add validation it). check this question... typically account class following, if every account required have valid supplier

class account < activerecord::base   belongs_to :supplier   validates_presence_of :supplier end 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -