Rails更新或重定向的路由

时间:2010-03-05 06:48:25

标签: ruby-on-rails routes

我不确定我是否正确行事。我有一个动作,我想复制,创建和保存新对象,如果用户登录,或重定向,如果他们没有登录。我没有在这里使用表单,因为我使用的程式化按钮与看起来像这样的图像:

<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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在您的routes.rb中尝试此操作:

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

:member - 与:collection相同,但适用于对特定成员进行操作的操作。