gpt4 book ai didi

ruby-on-rails - first_or_create 通过电子邮件然后保存嵌套模型

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:14 29 4
gpt4 key购买 nike

我的两个模型UserSubmission如下:

class User < ActiveRecord::Base
# Associations
has_many :submissions
accepts_nested_attributes_for :submissions

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :name, :role, :submission_ids, :quotation_ids, :submissions_attributes

validates :email, :presence => {:message => "Please enter a valid email address" }
validates :email, :uniqueness => { :case_sensitive => false }
end

class Submission < ActiveRecord::Base
belongs_to :user
attr_accessible :due_date, :text, :title, :word_count, :work_type, :rush, :user, :notes

validates :work_type, :title, :text,:presence => true
validates :text, :length => { :minimum => 250 }
validates :word_count, :numericality => { :only_integer => true }
end

我有一个表格可以收集这两个模型所需的数据。用户 Controller :

def index
@user = User.new
@user.submissions.build
end

def create
@user = User.where(:email => params[:user][:email]).first_or_create(params[:user])

if @user
redirect_to :root
else
render 'pages/index'
end
end

我想做的是首先通过提交的电子邮件检查用户是否已经存在于系统中。如果是这样,那么我想为该用户创建一个提交。否则同时创建用户和提交。

我对如何使用 first_or_create 方法做到这一点感到困惑。

感谢任何帮助。

最佳答案

first_or_create accepts a block .所以你可以这样做:

@user = User.where(:email => params[:user][:email]).first_or_create do |user|
# This block is called with a new user object with only :email set
# Customize this object to your will
user.attributes = params[:user]
# After this, first_or_create will call user.create, so you don't have to
end

关于ruby-on-rails - first_or_create 通过电子邮件然后保存嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644756/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com