You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中如何检查邮箱存在性并更新对应记录?求代码修正

Fixing Your Code to Update Records Based on Email Existence

Hey there! Let's walk through the issues in your current code and get it working exactly how you want—updating a contact's attributes only if their email already exists.

First, Let's Fix the Controller

Your current update method is creating a new contact instead of finding an existing one, which is why it's not working as intended. Plus, there's a double-render issue that will cause errors. Here's the corrected version:

def update
  # Look up the existing contact by the submitted email
  @contact = Contact.find_by(email: contact_params[:email])

  if @contact
    # If the contact exists, update their attributes (exclude email if you don't want to change it)
    if @contact.update(contact_params.except(:email))
      redirect_to root_path, notice: 'Contact was successfully updated.'
    else
      # Render the form again with validation errors
      render :new
    end
  else
    # If no contact matches the email, show an error message
    flash[:alert] = "No contact found with that email address."
    render :new

    # Optional: Uncomment below if you want to create a new contact instead of showing an error
    # @contact = Contact.new(contact_params)
    # if @contact.save
    #   redirect_to root_path, notice: 'New contact was successfully created.'
    # else
    #   render :new
    # end
  end
end

# Don't forget your strong params!
private
def contact_params
  params.require(:contact).permit(:email, :name, :image) # Add any other attributes you need to update
end

Key Fixes in the Controller:

  • We use find_by(email: ...) to check if a contact with the submitted email exists—this is the core of your requirement.
  • Removed the Contact.new call (that was creating a blank contact instead of updating an existing one).
  • Fixed the double-render issue: redirect_to and render can't both run in the same action, so we make sure only one happens based on the logic.
  • Added strong parameters (contact_params) to safely allow updates to specific attributes (never skip this in Rails!).

Next, Adjust the Model

You had a uniqueness validation commented out—if you want each email to be tied to only one contact (which makes sense for your use case), uncomment that line. Here's the cleaned-up model:

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 # Uncommented to ensure one contact per email
  validates :email, presence: true
end

Key Model Adjustment:

  • The validates :email, uniqueness: true ensures you won't end up with duplicate contacts using the same email, which aligns with your goal of updating existing records instead of creating duplicates.

How This Works Now

  1. When someone submits the update form, the controller first checks if a contact with that email exists.
  2. If it exists, the controller updates the contact's attributes (like name or image) and redirects to the root with a success message.
  3. If the update fails (e.g., invalid image type), it renders the form again with error messages.
  4. If no contact exists for the email, it shows an alert and renders the form—you can swap that logic to create a new contact instead if you prefer.

内容的提问来源于stack exchange,提问作者Atsu Mori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:54:49