use*_*583 8 ruby activerecord ruby-on-rails limit ruby-on-rails-3.1
我想限制用户可以创建的模型对象的数量.我已经尝试过以下但它不起作用.我理解rails 3.1中发生了一些变化,现在还不确定如何实现.
class User < ActiveRecord::Base
has_many :things, :limit => 5, :dependent => :destroy # This doesn't work
end
class Things <ActiveRecord::Base
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
Ale*_*tie 14
尝试这样的事情:
class User < ActiveRecord::Base
has_many :things
end
class Things <ActiveRecord::Base
belongs_to :user
validate :thing_count_within_limit, :on => :create
def thing_count_within_limit
if self.user.things(:reload).count >= 5
errors.add(:base, "Exceeded thing limit")
end
end
end
Run Code Online (Sandbox Code Playgroud)
编辑:更新为Rails 3
| 归档时间: |
|
| 查看次数: |
3902 次 |
| 最近记录: |