相关疑难解决方法(0)

捕获rails控制器中的所有异常

有没有办法在rails控制器中捕获所有未捕获的异常,如下所示:

def delete
  schedule_id = params[:scheduleId]
  begin
    Schedules.delete(schedule_id)
  rescue ActiveRecord::RecordNotFound
    render :json => "record not found"
  rescue ActiveRecord::CatchAll
    #Only comes in here if nothing else catches the error
  end
  render :json => "ok"
end
Run Code Online (Sandbox Code Playgroud)

谢谢

ruby-on-rails

87
推荐指数
4
解决办法
9万
查看次数

在Rails 4中的has_and_belongs_to_many关系中使用uniq

我正试图在这样的has_and_belongs_to_many关系上实现一个独特的约束:

class User
  has_and_belongs_to_many :foos, uniq: true
end
Run Code Online (Sandbox Code Playgroud)

因为我foos打电话时只想要独一无二user.foos,所以我添加了uniq选项.自升级到Rails 4以来,我开始收到以下警告:

弃用警告:不推荐使用User.has_and_belongs_to_many:foos声明中的以下选项:: uniq.请改用示波器块.例如,以下内容:

  has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment'
Run Code Online (Sandbox Code Playgroud)

应该改写如下:

  has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'
Run Code Online (Sandbox Code Playgroud)

我已经尝试了许多不同的组合,并通读源,但无法弄清楚如何编写唯一约束来删除警告?

activerecord ruby-on-rails ruby-on-rails-4

3
推荐指数
1
解决办法
4406
查看次数