开发者

Pass Error Messages When Using form_tag?

How can you pass an error messages coming from a model --> controller to view?

= form_tag :controller => "article", :action => "cre开发者_如何学Goate" do
  / how to retrieve error messages here?
  %p
    = label_tag :article, "Article"
    = text_field_tag :article
  = submit_tag "Submit Article"

I have this model:

class Article < ActiveRecord::Base
  attr_accessible :article

  validates         :article,      :presence => true
end

In my controller:

def create
  @article = Article.new(params[:article])

  if ! @article.save
    # how to set errors messages?
  end
end

I'm using Rails 3.0.9


The errors messages are stored in your model. You can access through the errors methods, like you can see in http://api.rubyonrails.org/classes/ActiveModel/Errors.html. An easy way to expose the error message is including the follow line in your view:

%span= @article.errors[:article].first

But, I belive you have to change your controller to be like that:

def new
  @article = Artile.new
end

def create
  @article = Artile.new params[:article]
  if !@article.save
    render :action => :new
  end
end

In the new action you don't need to try save the article, because the creation action already do that job. The new action exists, (basically) to call the new view and to provide support for validations messages.


The newmethod shouldn't save anything. create method should.

def create
  @article = Article.new(params[:article])

  if ! @article.save
    redirect_to root_path, :error => "ops! something went wrong.."
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜