本文介绍了Rails 模型 - 插入一条记录 - Ruby 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 Rails 4 很陌生.我创建了以下视图
I am very new to Rails 4. I have created following view
contact_us.html.erb
<%= form_tag({controller: "pages", action: "contact_us"}, method: "post", class: "nifty_form") do %>
<b> Add Product </b>
<br>
<p>
<%= label_tag 'Cname:' %>
<%= text_field_tag 'cname', @cname %>
<br>
<%= label_tag 'Cdetail:' %>
<%= text_field_tag 'cdetais', @cdetais %>
<% #email_field_tag 'pdetail', @pdetail %>
</p>
<%= submit_tag "Save" %>
<% end %>
型号: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<br/>" if @cname.nil? || @cname.empty?
flash.now[:error] << "Cdetais cannot be blank<br/>" if @cdetais.nil? || @cdetais.empty?
end
Contactu.create(cname: @cname, cdetais: @cdetais)
end
end
此代码有效.但是,我想知道有没有更好的方法?
This code works. But, I was wondering is there a better way?
我已经更改了代码,但现在它说#
I have changed the code, but now it saysundefined method `join' for #
@contact_us = Contactu.create(cname: @cname, cdetais: @cdetais)
if @contact_us.save
flash.now[:notice] << "Information saved </br>"
else
flash.now[:error] = @contact_us.errors.join('<br>')
end
推荐答案
当然还有更好的方法.
首先检查模型中是否存在给定的字段:
Firstly check if given fields are present in model:
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('<br>')
end
这篇关于Rails 模型 - 插入一条记录 - Ruby 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!