显示带模型验证的flash消息

时间:2015-08-04 15:20:50

标签: ruby-on-rails ruby-on-rails-3 validation flash-message

我有以下模型验证...

  validates :event_id, :uniqueness => {:scope => :email}
  validates_format_of :email, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
  validates_presence_of :email, :first_name, :last_name

..这是我的控制器......

def register_learner
    @event = Event.find(params[:event_id])
    begin
      EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
    end
end

此代码有效,但问题是它会默默地捕获错误。我想向用户和当前页面显示Flash消息。所以我尝试了这个......

   def register_learner
    @event = Event.find(params[:event_id])
    begin
      @registation = EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
      if !@registation.valid?
        flash[:notice] = @registation.errors
      end
    end
   end

...但如果验证失败,我会收到消息undefined method `valid?' for nil:NilClass

2 个答案:

答案 0 :(得分:1)

如果您使用new代替create!,您最终会得到一个可以告诉您valid? == false的实例。

在这种情况下你也不需要救援。

所以你可以这样做:

def register_learner
  @event = Event.find(params[:event_id])
  @registation = EventRegistration.new(
    first_name: params[:first_name], 
    last_name: params[:last_name], 
    email: params[:email], 
    event_id: params[:event_id]
  )
  flash[:notice] = @registation.errors unless @registation.valid?
end

此外,如果您可能已经有现有注册,则可以使用find_or_initialize_by,然后检查生成的对象是否为@registration.new_record?的新记录。

答案 1 :(得分:1)

谢谢chad_。这是票。对于一个完整的解决方案,这就是我所做的......

access: function (req, res) {
  var createFunctions = [];  

  while(x <= 1000) {
    createFunctions.push(function(done) {
      Model.create(etc).exec(function (err, ok) {
        if(err) return done(err); // err
        done(); //success
      });
    })

    x++;
  }

  // run in series, one by one
  async.series( createFunctions, function afterAll(err) {
    sails.controllers.mycontroller.other (req, res);

    //res.view('view/sampleview');
  });
},

other: function (req, res) {
  res.view('view/view');
},