【问题标题】:Rails link_to parameters dictating flow of control in controllerRails link_to 参数指示控制器中的控制流
【发布时间】:2013-04-06 07:36:49
【问题描述】:

所以我一直在努力尝试准确了解我可以在 Rails 中使用 link_to 做什么。我发现的有些东西是旧的,有些是新的,有些看起来与我所拥有的非常不同。具体来说,我试图在一个视图中有两个链接。一个是“加 1”,一个是“减 1”。当我到达控制器时,我想根据使用的链接从我的模型中添加或减去一个。以下是链接:

<%= link_to "Add 1", item, method: :put, title: item.name %>
<%= link_to "Minus 1", item, method: :put, title: item.name %>

我的控制器(item controller)方法是:

def update
    @item = current_user.item.find(params[:id])
    @item.quantity += #+1 or -1 depending on what is passed
    if @item.save
        flash[:success] = "Item updated."
    end
    redirect_to current_user
end

由于我使用 :put 调用 link_to 我不太确定如何区分哪个 :put 是哪个,因为除了链接名称之外,两个链接都是相同的。我想我正在使用 title: item.name 参数识别特定项目。是否仅通过item 路径标识?我应该把“:title”改成“+1”还是“-1”?我真的很感激澄清,因为这让我很困惑。我还在文档中注意到“html 选项”与“url 选项”,但我无法解读差异?谢谢!

【问题讨论】:

    标签: ruby-on-rails routes link-to


    【解决方案1】:

    您可以在 URL 中传递其他参数:

    <%= link_to "Add 1", item_path(item, perform: 'add'), method: :put %>
    <%= link_to "Sub 1", item_path(item, perform: 'sub'), method: :put %>
    
    def update
        @item = current_user.item.find(params[:id])
        params[:perform] == 'sub' ? @item.quantity -= 1 : @item.quantity += 1 
        if @item.save
            flash[:success] = "Item updated."
        end
        redirect_to current_user
    end
    

    或者也许将成员操作添加到您的item resource

    resources :items do
      member do
        put 'sub'
        put 'add'
      end
    end
    
    
    link_to "Add 1", [:add, item], method: :put
    link_to "Sub 1", [:sub, item], method: :put
    

    【讨论】:

    • title: item.name 在做什么?
    • 我认为“title: item.name”允许我识别控制器中的特定项目...
    • @osahyoun - link_to 示例有效。万分感谢。为了澄清。 “item_path”显然是路径,那么你传入一个实例和一个哈希? (项目是实例,“执行:'sub'”是哈希)在您发布的两个示例之间,是首选吗?再次感谢!
    • @MCP 完全正确。在哈希中传递名称/值对,成为 URL 参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多