2

我想檢查用戶提交的URL與正則表達式,如果URL不是以http://或https://開頭,那麼我想在前面加上http://開頭然後保存它。驗證網址|預先登錄http://

我有一些代碼,但我不知道如何將它合併到我的應用程序。這個代碼能工作嗎?並且我會在允許用戶創建鏈接之前將其合併到我的應用程序中以檢查網址。

我附上了下面的代碼和文件。由於

def add_http(link) 
    if (link =~ /http[s]?:\/\//) 
    link 
    else 
    "http://#{link}" 
    end 
end 

控制器https://gist.github.com/1279576

_form https://gist.github.com/1279580

型號https://gist.github.com/1279582

+0

可能重複的[添加HTTP(S)到URL如果它不存在?(http://stackoverflow.com/questions/7908598/add-https-url-if-its-not-there) – user456584

回答

8

固定的代碼位。這工作

before_save do |link| 
     link.url = "http://#{url}" unless link.url=~/^https?:\/\// 
    end 

感謝指導@bandito & @rubyprince的

+4

'before_create'只會在'creating'的情況下檢查url, record..ur最好使用'before_save',它將在'create'和'update'之前被調用。 – rubyprince

+0

非常感謝@rubyprince – Dru

5

的想法是好的。儘管如此,我會這樣寫:

def add_http uri 
    uri =~ %r(https?://) ? uri : "http://#{uri}" 
end 

更簡單了,沒有傾斜的牙籤! :-D

+1

謝謝,我把代碼放在哪裏,如何將它綁定到我的應用程序中? – Dru

+0

@ bandito的回答充分回答。我的回答純粹與代碼風格有關。 :-) –

6

你可以把它放在你的模型

class Link < ActiveRecord::Base 
    attr_accessible :title, :url 
    before_save :sanitize_url 

    private 
    def sanitize_url 
    if url_changed? 
    url = "http://#{url}" unless url =~ /^https?:\/\// 
    end 
    end 
end 
+0

謝謝,但這是行不通的。在將其保存到鏈接表之前,我會如何將正則表達式和條件後綴應用於任何url? – Dru

+1

它只是需要「self.url =」http://#{url}「除非url =〜/^https?:\/\ //」 –