2016-01-29 18 views
0

我想4.軌道4 - 方法來檢查匹配屬性

我使用的設計,並希望寫一個基於以下邏輯的申請後重定向路徑,使Rails中的應用程序。

我有一個包含:email屬性的用戶模型。我有一個組織模型,其中包含:email_format屬性(電子郵件屬性保存'@'後面的電子郵件地址部分。我有一個配置文件模型(其中包含用戶可以更改的用戶信息)

的關聯是:

用戶 - HAS_ONE:簡介 簡介 - belongs_to的:用戶,belongs_to的:組織 組織 - 的has_many:型材

如果用戶(註冊)輸入,包括電子郵件的電子郵件地址格式保存在數據庫中,然後我想將新用戶的配置文件與擁有該組織的用戶配置文件關聯起來匹配郵件格式。

例子:

新用戶:電子郵件= [email protected]

然後我檢查的組織表,看是否有:存儲email_attributes是 'cat.com'。

如果是,則新用戶的用戶配置文件與具有匹配的email_format的組織相關聯(因此相關配置文件表中的organisation_id設置爲與該組織id相匹配)。

這裏是在寫這篇我的最好的嘗試:

註冊控制器:

def after_sign_up_path_for(resource) 
    # check if the email address the user used to register includes the email format of an organisation 
    if @user.email.includes? @organisation(:email_format) 

    # if it does match, then update the user profile so that the org id equals the org id for the org that has the matching email format  

     @user.profile.organisation_id.update_attribute(organisation.id == (@organisation.email includes? :email_format)) 
    else 
     # set up a mandrill email sender to send this message 
     set_flash_message('We are just getting started and will get in touch with 
     you as soon as we have onboarded your organisation') 

    end 
    end 

我是新來的這一點,不知道如何查詢事情做好。任何指針將非常感激。

下一次嘗試

考慮下面的建議,我已經盡力了after_create回調如下添加到我的剖面模型:

after_create :update_organisation 

    def update_organisation 
    Profile.update_attribute(organisation_id: :matching_org_id) # Associations must be defined correctly for this syntax, avoids using ID's directly. 
    # Profile.save 
    end 


    def matching_org_id 
    if @self.user.email.includes? @organisation(:email_format) 
# how do you ask for the organisation with the matching email format id 

     profile.organisation_id: organisation.id 
    else 
     TBC 
    end 
    end 

這是行不通的。我不知道如何正確表達這種方法。目前,我收到一個錯誤,指出:

syntax error, unexpected '(', expecting keyword_then or ';' or '\n' if @self.user.email.includes? @organisation(:email_format) 

回答

0

第一個問題:

這部分是相當危險的:你可以有[email protected]返回假陽性。

if @user.email.includes? @organisation(:email_format) 

也許你可以使用存儲的正則表達式格式,並通過

/@cat.com$/ =~ @user.email 

檢查它在rubular.com

嘗試一下格式問題二:

更新方法應該是與此類似的東西。

@user.profile.update(organisation_id: @matching_organisation.id) 

您需要遍歷所有組織以查找匹配的組織。

第三個問題

我認爲這是一個不好的地方做這樣的操作的。您應該添加一個after_create hook到用戶模型,並將這些邏輯放在該方法中。

+0

嗨,這都是明智的建議。謝謝 - 我會試試看。如果我在我的email_format屬性中包含「a」,您認爲我的方法仍然很危險嗎? – Mel

+0

哈哈,雖然有好點。 「@」可能就足夠了 –