使用嵌套路由进行渲染时出错
当用户发送消息验证失败时,我试图维护一个漂亮的 URL。
我有一个如下所示的路由文件:
# 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
因此 new_user_message_path(@user) 返回:
/users/:user_id/messages/new
消息的 new.erb 视图生成正确的代码:
<form action="/users/:user_id/messages" .........
当验证失败时,它会显示表单错误,但会呈现错误的操作:
<form action="/messages" .........
所以当用户第二次提交表单时,“create”方法找不到user_id
这是我的控制器方法:
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
和我的表单视图:
<% 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 %>
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 %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试
try