【问题标题】:Rails 4 - method to check matching attributesRails 4 - 检查匹配属性的方法
【发布时间】:2016-05-06 15:23:44
【问题描述】:

我正在尝试在 Rails 4 中制作应用程序。

我正在使用设计并希望根据以下逻辑编写注册后重定向路径。

我有一个包含 :email 属性的用户模型。我有一个包含 :email_format 属性的组织模型(email 属性包含在“@”之后的电子邮件地址部分。我有一个配置文件模型(其中包含可以由用户自己更改的用户信息)。

这些关联是:

用户 - has_one: 个人资料 个人资料-belongs_to:用户,belongs_to:组织 组织 - has_many :profiles

如果用户(注册)输入的电子邮件地址包含保存在数据库中的电子邮件格式,那么我想将该新用户的个人资料与具有匹配电子邮件格式的组织相关联。

例子:

新用户的:email = bob@cat.com

然后我检查组织表以查看存储的任何 :email_attributes 是否为“cat.com”。

如果是,则新用户的用户配置文件与具有匹配 email_format 的组织相关联(因此相关配置文件表中的组织 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)

【问题讨论】:

    标签: ruby-on-rails methods devise


    【解决方案1】:

    第一个问题:

    这部分相当危险:您可以让bobcat.com@gmail.com 返回误报。

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

    也许您可以使用存储正则表达式格式并通过以下方式检查它

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

    rubular.com尝试格式

    第二个问题:

    更新方法应该和这个类似。

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

    您需要遍历所有组织以找到匹配的组织。

    第三个问题

    我认为这是一个不好的地方进行这种操纵。您或许应该将after_create hook 添加到用户模型并将这些逻辑放入该方法中。

    【讨论】:

    • 嗨,这都是明智的建议。谢谢 - 我会试一试。如果我在 email_format 属性中包含“a”,你认为我的方法仍然危险吗?
    • 大声笑,不过这很好。使用“@” 可能就足够了
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多