【问题标题】:Need to check whether email exists and then update record if it does. Rails需要检查电子邮件是否存在,如果存在则更新记录。导轨
【发布时间】:2018-05-25 21:07:23
【问题描述】:

我只是想根据电子邮件地址是否存在来更新记录的某些属性。

控制器:

def update
    @contact = Contact.new(contact_params)

        if @contact.update then
            redirect_to :root, notice: 'yes was successfully updated.'
            else
            render "new"
            end
        render "show"
    end

型号:

class Contact < ApplicationRecord
has_attached_file :image, styles: {large: "600x600>", medium: "300x300>", thumb: "150x150#"}
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
    #validates :email, uniqueness: true
    validates :email, presence: true
end }

绝对知道这有很多问题,希望得到一些帮助。

谢谢!

【问题讨论】:

    标签: mysql ruby-on-rails ruby activerecord


    【解决方案1】:

    当然,这里有很多需要改进的地方,首先让我明确回答你的问题:

    validates: email, uniqueness: true 
    

    通过在您的联系模型中添加该验证,更新方法将返回false,因此电子邮件不会被更新。您还可以通过在验证中添加 case_sensitive: false 来忽略 case_sensitive。 您应该记住,如果您有多个服务器/服务器进程(例如运行 Phusion Passenger、多个 Mongrel 等)或多线程服务器,则此验证不能保证唯一性。详细解释请查看this answer

    但是,这不适用于您上面粘贴的代码,让我解释一下原因:

    1) 更新方法需要传递 1 个参数,因此您的代码将在那里抛出一个 ArgumentError

    2)render在同一方法中出现多次:这会抛出以下错误

    在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。还要注意,redirect和render都不会终止action的执行,所以如果你想在redirect后退出一个action,你需要做一些类似“redirect_to(...) and return”的操作。

    你需要在那里重构你的代码。

    对于redirect_to: root,请务必先配置为根路由。

    3) 此行Contact.new(contact_params) 不返回现有记录。新方法会创建一个对象实例,因此您不会在那里更新任何内容。

    您的方法可能的解决方案是:

    helper_method :contact
    
    def update
      if contact.update(contact_params)
        flash[:success] = "Contact updated"
        redirect_to :root
      else
        render :edit
      end   
    end
    
    private
    
    def contact
      @contact ||= Contact.find(params[:id])
    end
    

    希望对你有帮助。

    【讨论】:

    • 感谢您的回复。当我在上面进行这些编辑并实施您的解决方案时,我收到一个错误。找不到带有 'id'= 的联系人
    • 那是因为您没有具有指定 id 的记录,或者您没有通过参数接收它。作为一个建议,我会创建一个 base_controller 来捕获错误并让这个控制器继承它。在这种情况下,您需要捕获的异常是 rescue_from ActiveRecord::RecordNotFound
    猜你喜欢
    • 2012-10-09
    • 2019-10-13
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    相关资源
    最近更新 更多