有关将记录插入数据库的帮助

时间:2011-01-25 16:11:41

标签: ruby-on-rails ruby activerecord

我想根据查询字符串参数的值在我的数据库中插入一条记录,只要我有脚手架方法并且它工作,它采用新方法中的值,然后是sumbit按钮单击,它将被插入数据库。

我怎样才能'跳过'点击按钮,所以它只是插入新方法?

代码:

@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

1 个答案:

答案 0 :(得分:0)

将此信息放入您要自动保存的操作中:

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

您可能想要添加的一些内容:仅在设置了params [:book]时保存:

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

还要考虑错误处理。如果这本书无法存储怎么办?