2
votes

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:

# app/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 %>
1
What's the issue you're having?user24359
the server output shows the message post, but then no error message is being returned. When the input matches the validation, the post works, when it doesn't nothing happens in the browser.James

1 Answers

2
votes

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.