Reputation: 429
I have a similar question to this guy Rails: How to limit number of items in has_many association (from Parent)
The key is I'd like to do this on the Array.push rather than on the :before_save attribute of the has_many association. In Java, I would probably make .windows private and create my own accessor. Not sure if I can do that with ActiveRecord methods that are available as the result of an association.
Any suggestions?
The spec I'm trying to get to pass is:
it "should not accept anymore windows" do
channel = Channel.new #with default 3 windows
channel.windows.length.should == 3
channel.windows.push Window.new
channel.windows.length.should == 3
end
Upvotes: 0
Views: 339
Reputation: 3085
You can use a before_add callback (scroll down to heading "Association callbacks") on your association to enforce the behavior
Should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with the before_remove callbacks; if an exception is thrown the object doesn’t get removed.
Upvotes: 2
Reputation: 5914
Why don't you control window insertion by making it through a method,
#chanel.rb
class Chanel
def add_window(window)
windows.push window if windows.length < 3
end
end
Upvotes: 0
Reputation: 12235
A little bit better than a callback, but not as clean as what you're trying to achieve, would be to do something like channel.windows << elem unless channel.windows.length > N
.
Upvotes: 1