我兩個型號User
和Submission
如下:first_or_create通過電子郵件,然後保存嵌套模式
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
方法做到這一點。
任何幫助表示讚賞。
我應該'合併'而不是分配給它,但這是我個人的偏好。更清潔一點。 –
謝謝,似乎是最乾淨的答案 – chell
只有在用戶不存在於數據庫中時纔會調用create。我發現這造成了一個問題,因爲當用戶已經存在時它不會創建提交對象 – chell