ruby-on-rails – first_or_create通过电子邮件然后保存嵌套模型

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 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,: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

猜你在找的Ruby相关文章