che*_*ell 8 ruby ruby-on-rails nested-attributes ruby-on-rails-3.2
我两个型号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
Run Code Online (Sandbox Code Playgroud)
我有一个表格,收集这两个模型所需的数据.用户控制器:
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
Run Code Online (Sandbox Code Playgroud)
我想要做的是首先通过提交的电子邮件检查用户是否已经存在于系统中.如果是,那么我想为该用户创建提交.否则,请同时创建用户和提交.
我对如何使用该first_or_create
方法做到这一点很困惑.
任何帮助赞赏.
Sub*_*has 13
first_or_create
接受一个块.所以你可以这样做:
@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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3655 次 |
最近记录: |