简体   繁体   中英

Reason for belongs_to and has_many associations in ruby-on-rails

I don't get why need both these associations?

Surely if you define one, it would naturally imply the other. Therefore making one of them redundant.

Is there ever a situation where you would have one and not the other?

For example if I define:

class Post < ActiveRecord::Base
  has_many :comments
end

why do I then need to define:

class Comment < ActiveRecord::Base
  belongs_to :post
end

Surely the above could be implied, and therefore use convention over configuration.

I'm just curious what the thinking was behind this! I'm sure there must be a good reason.

It's not that straight forward. For example if you have a belongs_to relation, the other end could represent a has_one or a has_many.

Secondly, sometimes you don't want the inverse association as it clogs up your model on the other end of the association. For example, you have a lot of classes referencing user but you don't need to know that a user has_many backorder_refirbished_car_parts

First for this code it should be belongs_to if i understand right, as has_one will search at Post for comment_id and i don't think its the case for you and comment who has post_id defined on it

class Comment < ActiveRecord::Base
  # has_one :post
  belongs_to :post 
 end

Second: if you don't want to define it, then You can do it but you will not be able to say:

 Comment.first.post

so if you don't need it don't write it.

Its not like needed . If you want only belongs_to or has_many association you could. There is not a dependency, If you followed convention of foreign key.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM