开发者

Help on Inserting a record to the db

开发者 https://www.devze.com 2023-02-06 11:48 出处:网络
I would like to insert a record into my db based on the values of querystring parameters, at the minute I just have the scaffold methods and it works, it takes the values at the in the new method, the

I would like to insert a record into my db based on the values of querystring parameters, at the minute I just have the scaffold methods and it works, it takes the values at the in the new method, then when the sumbit button is clicked, it is inserted into the db.

How can I 'skip' the clicking of the button, so it is inserted just in the new method?

Code:

@book = Book.开发者_如何学运维new(params[:book])
@book = Book.new({:user_id=>session[:user_id], :author=>session['test']})

respond_to do |format|
  if @book.save
    format.html { redirect_to(@book, :notice => 'Book was successfully created.') }
    format.xml  { render :xml => @book, :status => :created, :location => @book }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
  end
end


Put this in the action which you want to do a save automatically:

@book = Book.new(params[:book])
@book.save

Some thing you might want to add: Only save if if params[:book] is set:

unless params[:book].blank?
  @book = Book.new(params[:book])
  @book.save
end

Also think of error handling. What if the book could not be stored?

0

精彩评论

暂无评论...
验证码 换一张
取 消