Greg
Greg

Reputation: 429

How to limit the number of items that can be added to an ActiveRecord array

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

Answers (3)

Ransom Briggs
Ransom Briggs

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

nkm
nkm

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

ksol
ksol

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

Related Questions