Rails模型 – 插入记录 – Ruby方式
我是Rails 4的新手。我创建了以下视图
contact_us.html.erb
Add Product
型号:contactu.rb
class Contactu < ActiveRecord::Base end
pages_controller.rb
class PagesController < ApplicationController def index end def contact_us flash.now[:error] = "" if params[:commit] @cname=params[:cname] @cdetais=params[:cdetais] flash.now[:error] << "Pname cannot be blank
" if @cname.nil? || @cname.empty? flash.now[:error] << "Cdetais cannot be blank
" if @cdetais.nil? || @cdetais.empty? end Contactu.create(cname: @cname, cdetais: @cdetais) end end
这段代码有效。 但是,我想知道有更好的方法吗?
我已经更改了代码,但是现在它为##表示未定义的方法`join’
@contact_us = Contactu.create(cname: @cname, cdetais: @cdetais) if @contact_us.save flash.now[:notice] << "Information saved " else flash.now[:error] = @contact_us.errors.join('
') end
当然有更好的方法。
首先检查模型中是否存在给定的字段:
class Contactu < ActiveRecord::Base validate :cname, presence: true validate :cdetails, presence: true end
然后在你的控制器中:
@message = Contactu.create(params.permit(:cname, :cdetails)) if @message.save redirect_to blah, notice: "Thank's for the news" else flash[:error] = @message.errors.to_a.join('
') end
我可能会创建一个新的控制器和路由联系。
ContactController def index ... def create # on success go to index
路线:
Resources contact, only: [:index, :create]
表单:使用路径助手:
form_for **contact_path** ...
如果您希望链接是/ pages的一部分,那么也可以使用routes文件完成。
的确如此,请看:
http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller
但更好的是,RTFM,从教程开始开始;-)
def create @article = Article.new(params[:article]) @article.save redirect_to @article end