通过电子邮件first_or_create,然后保存嵌套模型 [英] first_or_create by email and then save the nested model
本文介绍了通过电子邮件first_or_create,然后保存嵌套模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型User
和Submission
如下:
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
我有一个收集这两个模型所需数据的表格.用户控制器:
I have a form which collects the data required by these two models. Users 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
我要做的是首先通过提交的电子邮件检查用户是否已存在于系统中.如果是这样,那么我想为该用户创建一个提交.否则,将同时创建用户和提交.
What I want to do is first check if the user already exists in the system by the email submitted. If so then I want to create a submission for that user. Otherwise create the user and submission at the same time.
我对如何使用first_or_create
方法执行此操作感到困惑.
I'm confused on how to do this with the first_or_create
method.
任何帮助表示赞赏.
推荐答案
first_or_create
接受阻止.因此,您可以按照以下步骤进行操作:
first_or_create
accepts a block. So you could do it as follows:
@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
这篇关于通过电子邮件first_or_create,然后保存嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文