Rails RSpec Tests for a has_many :through Relationship

I would recommend checking out a gem called Shoulda. It has a lot of macros for testing things like relationships and validations. If all you want is to test that the has_many relationship exists, then you could do the following: describe Post do it { should have_many(:categories) } end Or if you’re testing a has_many … Read more

rails model has_many of itself

This is a self-referential model, you can try something like this: class Event < ActiveRecord::Base belongs_to :parent, :class_name => “Event”, :foreign_key => “parent_event_id” has_many :child_events, :class_name => “Event”, :foreign_key => “child_event_id” end That way, you can call @event.parent to get an ActiveRecord Event object and @event.child_events to get an ActiveRecord collection of Event objects

how to avoid duplicates in a has_many :through relationship?

Simpler solution that’s built into Rails: class Blog < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :readers, :through => :blogs_readers, :uniq => true end class Reader < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :blogs, :through => :blogs_readers, :uniq => true end class BlogsReaders < ActiveRecord::Base belongs_to :blog belongs_to :reader end Note adding the :uniq … Read more

When will ActiveRecord save associations?

Unfortunately there are no such thing like associations_to_save. However there are some rules saying what is being saved when. You can find those here: http://guides.rubyonrails.org/association_basics.html. Points: 4.1.5 (belongs_to), 4.2.5 (has_one), 4.3.4 (has_many) and 4.4.4 (habtm). UPDATE: In case of has_many association, the child is saved on saving the parent if child.new_record? returns true (child was … Read more

Rails Model has_many with multiple foreign_keys

Found a simple answer on IRC that seems to work (thanks to Radar): class Person < ActiveRecord::Base belongs_to :father, :class_name => ‘Person’ belongs_to :mother, :class_name => ‘Person’ has_many :children_of_father, :class_name => ‘Person’, :foreign_key => ‘father_id’ has_many :children_of_mother, :class_name => ‘Person’, :foreign_key => ‘mother_id’ def children children_of_mother + children_of_father end end

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)