form_tag在show中呈现,但不在index中呈现

时间:2016-04-21 14:11:07

标签: ruby-on-rails ruby

我已经在我的控制器中设置了一个自定义操作,以便收听"收藏/收藏"食谱。我已经玩过,发现以下代码可以在我的show.html.erb中显示/使用收藏/不喜欢的按钮。

<% if current_user.present? && current_user.recipes.exists?(@recipe.id) %>
    <%= form_tag(controller: "recipes", action: "unfavorite", method: "post") do %>
        <%= submit_tag "Unfavorite"%>
      <% end %>
<% elsif current_user.present? %>
  <%= form_tag(controller: "recipes", action: "favorite", method: "post") do %>
      <%= submit_tag "Favorite"%>
      <% end %>
<% else %>
<% end %>

我试图将此操作添加到我的index.html.erb中,这样当您查看列表时,您可以从那里收到配方,我收到以下错误:

ActionController::UrlGenerationError in Recipes#index
No route matches {:action=>"unfavorite", :controller=>"recipes", :method=>"post"}

   <td><%= link_to 'Destroy', recipe, method: :delete, data: { confirm: 'Are you sure?' } %></td>
          <td><% if current_user.recipes.exists?(recipe.id) %>
                  <%= form_tag(controller: "recipes", action: "unfavorite", method: "post") do %>
                      <%= submit_tag "Unfavorite"%>
                  <% end %>
              <% else %>

我的index.html.erb代码如下:

  <tbody>
    <% @recipes.each do |recipe| %>
      <tr>
        <td><%= link_to recipe.title, recipe %></td>
        <td><%= link_to 'Source', recipe.url%></td>
        <td><%= recipe.description %></td>
        <% if logged_in? %>
          <td><%= link_to 'Edit', edit_recipe_path(recipe) %></td>
          <td><%= link_to 'Destroy', recipe, method: :delete, data: { confirm: 'Are you sure?' } %></td>
          <td><% if current_user.recipes.exists?(recipe.id) %>
                  <%= form_tag(controller: "recipes", action: "unfavorite", method: "post") do %>
                      <%= submit_tag "Unfavorite"%>
                  <% end %>
              <% else %>
                <%= form_tag(controller: "recipes", action: "favorite", method: "post") do %>
                    <%= submit_tag "Favorite"%>
                  <% end %>
              <% end %>
          </td>
        <% end %>
      </tr>
    <% end %>
  </tbody>

为什么这可以在show.html.erb中使用,但不能在index.html.erb中使用?

1 个答案:

答案 0 :(得分:2)

尝试将食谱id添加到表单

<%= form_tag(controller: "recipes", action: "unfavorite", id: recipe.id, method: "post") do %>