【发布时间】:2012-12-27 16:16:08
【问题描述】:
首先,我的资源在社区模型中使用 to_param 嵌套在 slug 中。
我在 example.com/shop/walmart/topic/14/edit 。
如果我在没有验证码输入的情况下按更新,显然应该让我再次返回编辑页面并显示 Flash 错误消息。
然而,它带我去 example.com/shop/14/topic/14/edit 。 community_name,主题是 :id。
所有字段的设置都与我在上一页输入的内容相同。
我怎样才能避免这种情况?它应该重定向到与上一页相同的 url。
routes.rb
resources :communities, :path => "shops", do
resources :community_topics, :path => "topics"
end
控制器
def simple_captcha_check
if !simple_captcha_valid?
flash[:error] = 'Wrong Captcha!'
if request.put? # We came from an edit request
@community_topic = CommunityTopic.find(params[:id])
@community_topic.attributes = params[:community_topic]
render :action => :edit
elsif request.post? # We came from a new request
@community_topic = CommunityTopic.new params[:community_topic]
render :action => :new
end
end
end
models/community.rb注意我在这里使用slug
def to_param
"#{community_name}"
end
views/community_topics/_form.html.erb
<%= form_for @community_topic, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :title, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :title, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :body, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :body, :class => 'text_area' %>
</div>
</div>
<div class="control-group">
<div class="controls">
<%= show_simple_captcha(:label => "human authentication") %>
</div>
</div>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
community_topic_index_path, :class => 'btn' %>
</div>
<% end %>
rake 路线 | grep community_topic
community_community_topics GET /shops/:community_id/topics(.:format) community_topics#index
POST /shops/:community_id/topics(.:format) community_topics#create
new_community_community_topic GET /shops/:community_id/topics/new(.:format) community_topics#new
edit_community_community_topic GET /shops/:community_id/topics/:id/edit(.:format) community_topics#edit
community_community_topic GET /shops/:community_id/topics/:id(.:format) community_topics#show
PUT /shops/:community_id/topics/:id(.:format) community_topics#update
DELETE /shops/:community_id/topics/:id(.:format) community_topics#destroy
顺便说一下,我在控制器中的 index 动作是这样的,而且工作正常!
community_topics_controller.rb #index
def index
@community = Community.find_by_community_name(params[:community_id])
@community_topics = @community.community_topics
respond_to do |format|
format.html # index.html.erb
format.json { render json: @community_topics }
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 routing