2

I am trying to maintain a pretty URL when having a user messaging with failed validation.

I have a routes file that looks like the following:

  # For logged users convenience
  #             example.com/messages
  # instead of: example.com/users/:user_id/messages
  map.resources :messages

  # For everyone else
  map.resources :users do |p|
    p.resources :messages
  end

So new_user_message_path(@user) returns:

/users/:user_id/messages/new

The message's new.erb view produces the correct code:

<form action="/users/:user_id/messages" .........

When validation fails it shows the form errors but renders the wrong action:

<form action="/messages" .........

So the second time the user submits the form the "create" method can't find the user_id

Here are my controller methods:

  def new
    @user = User.find(params[:user_id])
    @message = @user.messages.build
  end

  def create
    @user = User.find(params[:user_id])
    @message = @user.messages.new(params[:message])

    if @message.save
      flash[:notice] = 'Message saved'
      redirect_to user_url(@user)
    else
      render :action => "new" # Here is the problem I guess
    end
  end

And my form view:

<% form_for [@user, @message] do |f| %>
  <%= f.error_messages %>    
    Name:<%= f.text_field :name %>
    Email:<%= f.text_field :email %>
    Message:<%= f.text_area :body, :rows => 3 %>
    <%= f.submit 'Send' %>   
<% end %>
Ben Orozco
  • 4,361
  • 4
  • 33
  • 49
  • I don't understand what you're trying to do. Generally, messages are rendered within some other view with a route of its own, so there would not be any reason to have a route for messages, and therefore no reason to want a pretty URL for that route. – Steve Jorgensen Apr 15 '11 at 04:35

1 Answers1

4

try

<% form_for [:user, @message] do |f| %>
Naren Sisodiya
  • 7,158
  • 2
  • 24
  • 35
  • Actually worked with: <% form_for [:user, @message] do |f| %> Please edit your answer to mark it as correct – Ben Orozco Apr 15 '11 at 14:20