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.newcall (that was creating a blank contact instead of updating an existing one). - Fixed the double-render issue:
redirect_toandrendercan'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: trueensures 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
- When someone submits the update form, the controller first checks if a contact with that email exists.
- If it exists, the controller updates the contact's attributes (like name or image) and redirects to the root with a success message.
- If the update fails (e.g., invalid image type), it renders the form again with error messages.
- 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
相关产品推荐
相关产品推荐

