ruby-on-rails – first_or_create通过电子邮件然后保存嵌套模型
发布时间:2020-12-16 19:15:39 所属栏目:百科 来源:网络整理
导读:我的两个模型用户和提交如下: 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,:subm
我的两个模型用户和提交如下:
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,: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方法执行此操作感到困惑. 任何帮助赞赏. 解决方法
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容