postgresql - Is the first has_many redundant? - Ruby on Rails Active records associations -


rails 4.2 newbie:

2 questions;

1) first has_many redundant? since name plural of save class?

can have only:

has_many   :savers, through: :saves, source: :saver 

or better;

has_many   :savers, through: :saves 

if answer yes, can set "dependent: :destroy"?

class post < activerecord::base   belongs_to :user   has_many   :saves, class_name: "save", foreign_key: "saver_id", dependent: :destroy                           has_many   :savers, through: :saves, source: :saver end  class save < activerecord::base   belongs_to :saver, class_name: "user"   validates :saver_id, presence: true end   class user < activerecord::base   has_many :posts, dependent: :destroy   ... end 

2) typical blog model, user can 'save' posts posted user timeline. model make use best practices? specially in db performance, doing join posts saved user. 'save' table have 100mm rows?

lets first alter example bit make naming less confusing:

class user   has_many :bookmarks   has_many :posts, through: :bookmarks end  class post   has_many :bookmarks   has_many :users, through: :bookmarks end  class bookmark   belongs_to :user   belongs_to :post end 

lets have @ query generated when @user.posts

irb(main):009:0> @user.posts   post load (0.2ms)  select "posts".* "posts" inner join "bookmarks" on "posts"."id" = "bookmarks"."post_id" "bookmarks"."user_id" = ?  [["user_id", 1]] => #<activerecord::associations::collectionproxy []> 

now lets comment out has_many :bookmarks , reload:

class user   # has_many :bookmarks   has_many :posts, through: :bookmarks end 

irb(main):005:0> @user.posts activerecord::hasmanythroughassociationnotfounderror: not find association :bookmarks in model user 

so no, first has_many not redundant - in fact core of how has_many through: works. setup shortcut of sorts through relation.

note in has_many :posts, through: :bookmarks :bookmarks name relation joining through. not table contains joins.

to fix original code need do:

class post < activerecord::base   has_many   :saves, dependent: :destroy                has_many   :savers, through: :saves end  class save < activerecord::base   belongs_to :saver, class_name: "user"   belongs_to :post # join table 1 relation pretty worthless.   validates :saver_id, presence: true end  class user < activerecord::base   has_many :posts    has_many :saves, dependent: :destroy   has_many :posts, through: :saves end 

note don't need half junk - if have has_many :savers, through: :saves activerecord relation saver itself. want use dependent: destroy on join model - not on post relation remove posts user has "saved" - written others!


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -