我有一个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],但我不明白如何解决它。
另外,在控制器中添加这个过滤器是否正确?也许它必须在模型级别?或者最好在生成视图时动态添加前缀,所以我必须把它放在那里?
非常感谢!