我有一个应用,如果有人正在创建重复的author
,我想在此警告他们。我为before_action
方法设置了create
过滤器,如下所示:
def check_for_duplicates
@duplicates = Author.where(first_name: @new_author.first_name, last_name: @new_author.last_name)
if @duplicates.count != 0
## THE NEXT LINE IS WHAT I NEED TO FIGURE OUT ##
data: {confirm: "You already have an author with this name. Are you sure you want to create another one?"}
end
end
我目前收到以下服务器错误:
SyntaxError - syntax error, unexpected ':', expecting keyword_end
data: {confirm: "You already have ...
^
/Users/lizbayardelle/Code/MMR/app/controllers/authors_controller.rb:80: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
...irect_to authors_path, notice "Sorry, you don't have permiss...
... ^:
app/controllers/authors_controller.rb:73:in `'
但是,这是预料之中的,因为我知道这行不是你做的。我无法通过link_to
执行此操作,因为我必须先检查它是否重复。
我已经检查了其他SO问题(例如this),似乎所有内容都涉及一个相当复杂的页面javascript解决方案。
在控制器内部是否有完成此操作的整洁方法?
data-confirm
属性实际上只是使用Rails UJS在javascript中提供的事件处理程序的一种简便方法。您无法从后端触发确认对话框,整个想法只是倒退。
正如已经建议的,如果您想从前端进行此验证,则需要一条路由,您可以在其中通过名称和last_name查找用户。您甚至不必返回JSON。只需执行HEAD请求,然后检查状态是否为200 OK或302 FOUND或404 NOT FOUND。
如果无法管理服务器,请在模型中添加标志属性和自定义验证:
class Author < ApplicationRecord
# this creates an attribute without a db column.
attribute :dup_warning_displayed, :boolean, default: false
validate :name_duplication, unless: :dup_warning_displayed?, on: :create
# ...
def name_duplication
if self.class.where(first_name: first_name, last_name: last_name).any?
errors.add(:base, "You already have an author with this name. Are you sure you want to create another one?")
dup_warning_displayed = true
end
end
end
然后您需要通过表格传递dup_warning_displayed
属性:
<%= form_for(@author) do |f| %>
# ...
<%= f.hidden_field :dup_warning_displayed if @author.dup_warning_displayed? %>
# ...
<% end %>