将数据从一个控制器的索引方法传递到另一个控制器的创建

Pass data from index method of one controller to create of another

我生成了一个设计模型用户,我还有一个对话控制器。我正在显示所有用户,除了已登录的用户,我正在尝试在 user1 和 user2 之间创建一个新的对话,但我被重定向到对话控制器的索引方法,而不是创建一个。我从这个 link 了解到,从一个控制器到另一个控制器制作 post 是个坏主意 Rails: How to POST internally to another controller action?

我还尝试在 Users 控制器中创建一个 send_message 方法,并在路由中将其定义为 post,但我被重定向到 Users 控制器的 show 方法。

这样做的干净方法是什么?

class UsersController < ApplicationController
  before_action :authenticate_user!

  def index
    @users = User.where.not(id: current_user.id)
  end

  def send_message
    # @conversation = Conversation.new(conversation_params)
    # if @conversation.save
    #
    # end
  end

end

index.html.erb

    <div class="col-xs-12 col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1> User's index </h1>

<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Email</th>
      <th>Created</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.email %></td>
        <td><%= time_ago_in_words(user.created_at) %> ago</td>
        <td>
          <div class="btn-group">
            <%= link_to 'Send', conversations_path(sender_id: current_user.id, recipient_id: user.id) %>
          </div>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>


</div>

编辑:

private
  def conversation_params
     params.require(:conversation).permit(:sender_id, :recipient_id)
  end


<ActionController::Parameters {"_method"=>"post", "authenticity_token"=>"394MDmcVVelccU//8ISYeqmk146exYc6G7SrrAhbCA/yQ/K8KTpSn/0EkXlZ4hB/g==", "recipient_id"=>"1", "sender_id"=>"3", "controller"=>"conversations", "action"=>"create"} permitted: false>

默认情况下 link_to 助手发送 GET 请求。您可以通过在其选项中添加 method: :post 来实现。

<%= link_to 'Send', path, method: :post %>

您可以重定向到 new_converstion_path 而不是 conversations_path。 link 默认情况下发送 GET 而不是 POST 请求。