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
What Are Factory_Girl Transient Attributes? Why Would I Use One
How to Get Systemd to Restart Rails App with Puma
How to Refresh a Page with Turbolinks
How Do Get a Random Datetime Rounded to Beginning of Hour in Rails
Cloning an Array with Its Content
Gemfile.Lock Always Has Changes Not Staged for Commit
How to Implement Composite Primary Keys in Rails
Normal Variables VS Instance Variable in Ruby, Whats the Difference
Accessing Headers from Sinatra
How to Merge Two Hashes That Have Same Keys in Ruby
Should Rbenv Be Installed System-Wide, or at a User Level
Single Custom Param Name in Routes for Nested Resources Rails 4.1
How to Return a Fixed Length Binary Representation of an Integer in Ruby
Instance Variables Inheritance
How to Upload a Local File to a Carrierwave Model
Rails Installation Error :The 'Atomic' Native Gem Requires Installed Build Tools