开发者

Error Rendering with Nested Routes

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 %>


try

<% form_for [:user, @message] do |f| %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜