2010-03-05 75 views
0

我不知道我是否正确执行此操作。我有一个操作,我想要复制,创建,并保存一个新的对象,如果用户登录,或者重定向,如果他们没有登录。我不在这里使用一个表单,因为我正在使用一个风格化的按钮,图像,看起来像这样:更新或重定向的Rails路由

<a href="/lists/add/<%= @list.id %>" class="button"> 
    <span class="add_list">Learn these words</span> 
</a> 

和行动看起来是这样的:

def add  
    if is_logged_in? 
     list = logged_in_user.copy_list(params[:id]) 
     if list.save 
     flash[:notice] = "This list is now in your stash." 
     redirect_to stash_zoom_nav_quiz_path(list, "zoomout", "new", "quizoff") 
     else 
     flash[:notice] = "There was a problem adding this list." 
     redirect_to :back 
     end 
    else 
     redirect_to :controller => "users", :action => "signup_and_login", :list_id => params[:id]  
    end 
    end 

map.resources :lists, :collection => {:share => :get, :share_callback => :get, :add => :put} 

我已经加入这种动作为:把我的路线,我不知道这是否是正确的或如果其他东西是正确的方式,甚至可以做到这一点。任何帮助表示赞赏。

回答

2

具体回答你的问题是

map.resources :lists, :collection => { :share => :get, :share_callback => :get }, :member => { :add => :put } 

add行动工作的部件,而不是一个集合。

但你的代码还有其他问题。首先,你应该总是使用Rails助手来生成URL。其实路径/lists/add/<%= @list.id %>是错误的。它应该是/lists/<%= @list.id %>/add

变化

<a href="/lists/add/<%= @list.id %>" class="button"> 
    <span class="add_list">Learn these words</span> 
</a> 

<% link_to add_list_path(@list), :class => "button" do %> 
    <span class="add_list">Learn these words</span> 
<% end %> 

控制器可以简化。在前过滤器中移动is_logged_in?检查。

class MyController < ActionController::Base 

    before_filter :require_logged_user, :only => %w(add) 

    def add  
    list = logged_in_user.copy_list(params[:id]) 
    if list.save 
     flash[:notice] = "This list is now in your stash." 
     redirect_to stash_zoom_nav_quiz_path(list, "zoomout", "new", "quizoff") 
    else 
     flash[:notice] = "There was a problem adding this list." 
     redirect_to :back 
    end 
    end 

    protected 

    def require_logged_user 
    if !is_logged_in? 
     redirect_to :controller => "users", :action => "signup_and_login", :list_id => params[:id] 
    end 
    end 

end 
+0

只是出于好奇,会错误标记成员作为集合的负面影响是什么? – TenJack 2010-03-09 05:44:14

+0

也谢谢你的帮助,我不知道你可以用link_to创建一个块! – TenJack 2010-03-09 05:56:09

+0

有一件事,我想我应该在这里使用POST方法b/c我创建一个新记录,但是,如果我使用POST或PUT,我会得到一个“ActionController :: UnknownAction”路由错误。看来GET是单词的唯一方法,这可以吗? – TenJack 2010-03-09 06:19:35

0

试试这个在您的routes.rb:

map.resources :lists, :member => {:add => :put}, :collection => {:share => :get, :share_callback => :get} 

:成员 - 同:集合,但对于特定成员上进行操作的行为。