1

I am creating a scheduling system in Ruby Rails. The system is composed of Customers, Resources, and Bookings. There is many to one with Booking to Customer and Resources. A customer and resource can have many bookings.

Booking has customer_id and booking_resource_id I thought should be protected. I also used booking_resource as the model because Resource conflicted with activeadmin.

I am using the validates_overlap gem that allows easily to create a overlapping validation with a scope to :booking_resource_id ( https://github.com/robinbortlik/validates_overlap) . The goal is we can never schedule the same resource at the same time.

The whole thing works under mass assignment but as soon as I put booking_resource_id as protected, add the individual assignments in the controller the validation is by passed.

How can I validate a protected attributed?

I read http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/ but I seem a little bit cornered. If I used attributes= and override mass assignment protected what is the point?

class Booking < ActiveRecord::Base
  belongs_to :customer
  belongs_to :booking_resource
  attr_accessible :approved, :approvedBy, :end, :start, :title
  attr_protected :customer_id, :booking_resource_id
  validate :start_cannot_be_future
  validates :start, :end, :overlap => {:scope => :booking_resource_id}

  def start_cannot_be_future
    if self.start > self.end
      errors.add(:start, "Date can't be in the future")
    end
  end
end
4

1 回答 1

1

首先,如果您使用 attr_accessible 那么您不需要使用 attr_protected 因为您无法访问的属性将自动受到保护。

其次,我不明白你为什么要保护booking_resource_id。我的意思是,你怎么知道要预订的资源是什么?是的,也许对于编辑它应该受到保护,但对于创建我不这么认为。

因此,如果您需要指定不同的受保护属性,我建议您查看将包含在新 Rails 版本中的新strong_parameters gem。这个 gem 为您提供了一种很好的方法来指定要在控制器中列入白名单的属性,并且您可以为每个控制器操作创建不同的白名单,我认为在这种情况下您需要这样做。

于 2012-10-08T01:09:20.497 回答