Best Practice for Limiting the Number of Associations Within a Has_Many Relationship

Best practice for limiting the number of associations within a has_many relationship?

At first, if your users table has foreign key account_id then you need to use

class User
belongs_to :account
end

In this way you will ensure that User can be associated just to one Account.

If you want to limit that Account can have e.g. at most 3 users then you can define the following validation:

class User
validates_each :account do |user, attr, value|
user.errors.add attr, "too much users for account" if user.account.users.size >= 3
end
end

and as a result you will not be able to create new user for account if account has already 3 users.

Rails: `includes` a `has_many` relation with `limit`

There is a note tucked away in the associations documentation under "Eager loading of associations":

If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects.

So, it is behaving as documented even though that might not be the intuitive behaviour.

The work around is to not eager load the limited associated and to access separately afterwards. As you point out that's not ideal but it is almost certainly preferable to loading all of the associated objects without a limit.

limit the number of objects returned in a has_many

Just add a limit option to the has_many association:

class User < ActiveRecord::Base
has_many :photos, :limit => 8
end

EDIT

According to your needs:

class User < ActiveRecord::Base
has_many :all_photos, :class_name => "Photo"
has_many :photos, :limit => 8
end

note: changed 'class' to 'class_name' in the all_photos association

has_many :through - Apply a limit to the join table

Perhaps its better to separate the relation definition from the query you want to make.

class Post
has_many :commenters, through: :comments

def last_commenters
comments.order('created_at DESC').limit(10).map{|c|c.commenter}.uniq
end
end

Disclaimer: code not tested.



Related Topics



Leave a reply



Submit