如何检查回形针是否存在重复文件但仅在当前板中
How to check if duplicate file exists with paperclip but only in current board
我目前用 :fingerprint => :post_file_fingerprint
保存指纹的回形针,我的路线设置如下:
resources :boards, :path => '' do
resources :posts, :path => 'thread' do
resources :replies
我如何检查新生成的指纹是否存在 post_file_fingerprint
,如果不存在则不创建 post。
目前我的 post.rb
:
before_save :check_exists
def check_exists
if Post.exists?(:post_file_fingerprint [:fingerprint.to_s])
flash.now[:error] = "Duplicate"
render @board
end
end
但是此代码仍然允许 post 保存,并且没有基于板的检查。
我假设你想在模型中闪光。没有办法做到这一点,因为 flash
是 ActionController::Base
.
中定义的方法
如果您想验证您的 Post
模型,您应该实施自定义验证。
before_save :check_exists
def check_exists
errors.add(:post_file_fingerprint, "Duplicate") if Post.exists?(post_file_fingerprint: [:fingerprint.to_s])
end
我不确定您的检查条件是否正常,因为您提供的相关细节太少。请确保有效。
在你的控制器中
def create
# some code
if @post.save
redirect_to @post
else
flash[:error] = @post.error.messages
render 'new'
end
end
工作原理如下:
在保存模型之前,将启动 AR 回调,如果 Post
无效 — 模型实例将根据您提供的消息设置为无效。
AR 不会将无效模型保存到数据库中,然后您将 flash[:error]
设置为自定义错误消息。
更多详情here。
希望对您有所帮助。
更新
我测试了代码并做了一些改进。以下示例有效:
def check_exists
errors.add(:post_file, "Duplicate") if Post.exists?(post_file_fingerprint: attributes['post_file_fingerprint'])
end
我目前用 :fingerprint => :post_file_fingerprint
保存指纹的回形针,我的路线设置如下:
resources :boards, :path => '' do
resources :posts, :path => 'thread' do
resources :replies
我如何检查新生成的指纹是否存在 post_file_fingerprint
,如果不存在则不创建 post。
目前我的 post.rb
:
before_save :check_exists
def check_exists
if Post.exists?(:post_file_fingerprint [:fingerprint.to_s])
flash.now[:error] = "Duplicate"
render @board
end
end
但是此代码仍然允许 post 保存,并且没有基于板的检查。
我假设你想在模型中闪光。没有办法做到这一点,因为 flash
是 ActionController::Base
.
如果您想验证您的 Post
模型,您应该实施自定义验证。
before_save :check_exists
def check_exists
errors.add(:post_file_fingerprint, "Duplicate") if Post.exists?(post_file_fingerprint: [:fingerprint.to_s])
end
我不确定您的检查条件是否正常,因为您提供的相关细节太少。请确保有效。
在你的控制器中
def create
# some code
if @post.save
redirect_to @post
else
flash[:error] = @post.error.messages
render 'new'
end
end
工作原理如下:
在保存模型之前,将启动 AR 回调,如果 Post
无效 — 模型实例将根据您提供的消息设置为无效。
AR 不会将无效模型保存到数据库中,然后您将 flash[:error]
设置为自定义错误消息。
更多详情here。
希望对您有所帮助。
更新
我测试了代码并做了一些改进。以下示例有效:
def check_exists
errors.add(:post_file, "Duplicate") if Post.exists?(post_file_fingerprint: attributes['post_file_fingerprint'])
end