Link 没有 'post' 正确的数据来采取行动。 (只得到最后一个ID)

Link does not 'post' the right data to action. (only get last id)

我有一个列出所有新闻文章的页面和它们旁边的编辑按钮(管理)。编辑按钮会将您带到编辑页面并发送相应文章的数据。编辑按钮总是选择最后生成的 id。我的循环有什么问题?


资源:

routes.rb

  get   '/news/manage', to: 'news#manage'
  match '/news/edit', to: 'news#edit', :via => :post

news_controller.rb

before_action do
  setup(session[:current_user_id])
end

def edit
  @article = News.find(params[:id])
end

def manage
end

private
  def setup(session)
    @user = User.find(session)
    @articles = News.all
  end

manage.html.erb

<%= form_tag '/news/edit', method: "post" do %>
  <%= @articles.each do |article| %>
        <%= content_tag :button, type: "submit" do %>
          <%= content_tag :i do %><%end%>
        <%end%>
      <%= content_tag :input, name: "id", value: article.id do %> <%end%>
  <%end%>
<%end>

edit.html.erb

<%= content_tag :textarea, name: "content", rows: "20" do %>
    <%= @article.content.gsub(/\s+/, " ")%>
<%end%>
<%= content_tag :input, name: "id", type: "hidden", value: @article.id do %> <%end%>

问题是您的表单有多个生成的同名元素:"id"。它不知道使用哪一个,所以它使用最后一个。

现在的想法....如何使每篇文章的名称唯一?这可能不是最好的解决方案,但是...不要

让您的表单独一无二。更改此代码:

<%= form_tag '/news/edit', method: "post" do %>
  <%= @articles.each do |article| %>
        <%= content_tag :button, type: "submit" do %>
          <%= content_tag :i do %><%end%>
        <%end%>
      <%= content_tag :input, name: "id", value: article.id do %> <%end%>
  <%end%>
<%end>

对此:

<%= @articles.each do |article| %>
  <%= form_tag '/news/edit', method: "post" do %>
        <%= content_tag :button, type: "submit" do %>
          <%= content_tag :i do %><%end%>
        <%end%>
      <%= content_tag :input, name: "id", value: article.id do %> <%end%>
  <%end%>
<%end>

首先在 routes.rb

中进行以下更改

替换

match '/news/edit', to: 'news#edit', :via => :post

get '/news/:id/edit' => 'news#edit', as: :edit_news

然后替换

<%= form_tag '/news/edit', method: "post" do %>
  <%= @articles.each do |article| %>
        <%= content_tag :button, type: "submit" do %>
          <%= content_tag :i do %><%end%>
        <%end%>
      <%= content_tag :input, name: "id", value: article.id do %> <%end%>
  <% end %>
<% end %>

<%= @articles.each do |article| %>
  <%= link_to "Edit", edit_news(article) %>
<% end %>

this will create `Edit` link for each article and clicking on it will take you to edit page.

如果你想显示 link 作为按钮你需要写 css.