0
我有一个bookmark
型号,具有:url
属性。我需要将它以正确的格式保存在数据库中:使用http://
或https://
前缀。保存到数据库之前编辑数据
所以,在bookmarks_controller
我做了一个before_filter
为create
行动:
class BookmarksController < ApplicationController
before_filter :standardise_urls, only: :create
.
.
.
def create
@bookmark = current_user.bookmarks.build(params[:bookmark])
if @bookmark.save
flash[:success] = "Bookmark created!"
redirect_to root_url
else
render 'static_pages/home'
end
end
.
.
.
private
def standardise_urls
if params[:bookmark][:url] != /https?:\/\/[a-zA-Z0-9\-\.]+\.[a-z]+/
params[:bookmark][:url] = "http://#{params[:bookmark][:url]}"
end
end
end
但它不工作。我希望它添加http://
前缀链接,没有它,当用户添加它们。但它会继续向所有创建的链接添加前缀。
我认为错误在重复params[:bookmark][:url]
,但我不明白如何解决它。
此外,在控制器中添加此过滤器是否正确?也许它必须在模型级别?或者,当生成视图时,最好在动态添加前缀,所以我必须把它放在那里?
非常感谢!