开发者

Error Messages with form_tag in separate controller Rails 3

开发者 https://www.devze.com 2023-02-08 00:10 出处:网络
I used a form_tag to access an action from a different controller in one of my Rails views. This has caused trouble for me rendering the error message. I am also using JQuery which could potentially b

I used a form_tag to access an action from a different controller in one of my Rails views. This has caused trouble for me rendering the error message. I am also using JQuery which could potentially be causing an issue. I have read that form_tag is not bound to a model, so that might mean that something like validates_uniqueness_of might not work. Would appreciate help understanding validations with form_tag!

For reference, here is my controller:

# a开发者_开发问答pp/controllers/posts_controller.rb
def create
  @post = Post.new
  @post.text = params[:text]
  @post.user_id = current_user.id
  @post.save

  respond_to do |format|
    if @post.save
      format.js
      format.html { redirect_to(username_path(:username => current_user)) }
      format.xml  { render :xml => @post, :status => :created, :location => @post }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
    end
  end
end

And my view (on my User model)

    
# app/views/users/show.html
<% form_tag({:controller => "posts", :action => "create"}, :method => "post", :class => 'newpost') do %>
  <%= error_messages_for :post  %>
  <%= text_field_tag :text, params[:text] %>
  <%= image_submit_tag("../images/add.png", :border => 0, :class => "submitadd") %>
%lt;% end %>


I think the issue is that might be that you are double saving and somehow clearing some error messages. You could try the following instead:

# app/controllers/posts_controller.rb
def create
  @post = Post.new
  @post.text = params[:text]
  @post.user_id = current_user.id

  respond_to do |format|
    if @post.save
      format.js
      format.html { redirect_to(username_path(:username => current_user)) }
      format.xml  { render :xml => @post, :status => :created, :location => @post }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
    end
  end
end

After calling render :action => 'new' you should be able to view the error messages with:

<%= error_messages_for @post  %>

You can verify that there are errors by displaying @post.errors in your log as well.

0

精彩评论

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