我有两种型号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
我有一个表格来收集这两个模型所需的数据。用户控制器:
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
方法执行此操作感到困惑。
任何帮助表示赞赏。