ruby on rails - first_or_create by email and then save the nested model -


i 2 models user , submission follows:

class user < activerecord::base   # associations   has_many :submissions   accepts_nested_attributes_for :submissions    # setup accessible (or protected) attributes model   attr_accessible :email, :name, :role, :submission_ids, :quotation_ids, :submissions_attributes    validates :email, :presence => {:message => "please enter 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 

i have form collects data required these 2 models. users controller:

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 

what want first check if user exists in system email submitted. if want create submission user. otherwise create user , submission @ same time.

i'm confused on how first_or_create method.

any appreciated.

first_or_create accepts block. follows:

@user = user.where(:email => params[:user][:email]).first_or_create |user|   # block called new user object :email set   # customize object   user.attributes = params[:user]   # after this, first_or_create call user.create, don't have end 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -