is possible limit the number of has_many objects?

Hi. On the document the has_many :limit option : The :limit option lets you restrict the total number of objects that will be fetched through an association.

I'm a little confused about this explanation. is fetched means it can save more but restircted numbers to retrieve at once?

For example, we can have wife/husband up to 1 (unless arab..) I suppose class Me < ActiveRecord::Base      has_many :wife end because i can have a wife or not. so it is not 1:1, isn't it? but at the same time i want to limit the number of wife to just 1. how can i represent this relationship into active record?

Thanks.

Use has_one :wife This allows 0 or 1 wife unless your validations require that a wife exists

See http://guides.rubyonrails.org/association_basics.html for an explanation of the various associations.

Use has_one :wife

On second thoughts I am not sure about this, writing

class Wife < ActiveRecord::Base belongs_to :husband end

may well get you into serious trouble.

Colin Law wrote:

Use has_one :wife

On second thoughts I am not sure about this, writing

class Wife < ActiveRecord::Base   belongs_to :husband end

may well get you into serious trouble.

This is actually one of the more interesting examples. In the specific case of husband and wife the design pattern that most people use is something like the following:

Story: Assuming the relationship is based on one spouse at a time a many-to-many relationship is still used to track the history of marriages between people. The one-spouse-at-a-time rule would then be implemented in validation code.

Person < ActiveRecord::Base   has_many :marriages   has_many :spouses, :through => :marriage

  validate :one_spouse_at_a_time

  def current_spouse     # find and return the person's current spouse   end

  protected   def one_spouse_at_a_time     # do the validation here   end end

Something along that line anyway.

That reminded me of a really funny article:

"Gay marriage: the database engineering perspective"

Amusing, regardless of one's opinion of the issue.

--Matt Jones