导轨|在创建后在显示页面上显示url参数

时间:2017-02-25 00:59:10

标签: javascript ruby-on-rails actioncable

我通过link_to

将网址参数添加到new.html.erb页面
<%= link_to 'Message', new_personal_message_path(receiver_id: 1010) %>

正确地在URL中显示为

  

example.com/personal_messages/new?receiver_id=1010

我能够通过简单的@receiver = User.find_by(id: params[:receiver_id])

在我的控制器中引用它

在new.html.erb上我有这个表单来创建一个新的对话:

<%= form_for @personal_message do |f| %>
  <%= hidden_field_tag 'receiver_id', @receiver.id %>
  <%= f.text_area :body, class: "personal_message_textarea", placeholder: "Chat with us...", :autofocus => true %>
  <%= hidden_field_tag :conversation_id, params[:id] || session[:conversation_id] %>
  <%= f.submit " ", placeholder: "Chat with us!", class: "personal_message_submit" %>
<% end %>

它会自动将用户重定向到网址显示为

的节目页面
  

example.com/conversations/1

但我还希望它还能在URL参数中显示新创建的user_id(我的控制器中有一个方法可以在创建时自动创建用户帐户),如下所示:

  

example.com/conversatinos/1?user_id=23&receiver_id=1010

personal_messages控制器中的新方法

def new
    redirect_to conversation_path(@conversation) and return if @conversation
    @personal_message = PersonalMessage.new
    @site = Site.find_by(id: cookies[:siteid]) #used to pull site description
end

在personal_messages控制器中创建方法

  def create
    @conversation ||= Conversation.create(author_id: cookies[:user_id],
                                         receiver_id: @receiver.id)
    @personal_message = current_user.personal_messages.build(personal_message_params)
    @personal_message.conversation_id = @conversation.id
    @personal_message.save!
    flash[:success] = "ok!"
    redirect_to conversation_path(@conversation)
  end

1 个答案:

答案 0 :(得分:0)

已修复:personal_messages控制器

  def create
    @conversation ||= Conversation.create(author_id: cookies[:user_id],
                                         receiver_id: @receiver.id)
    @personal_message = current_user.personal_messages.build(personal_message_params)
    @personal_message.conversation_id = @conversation.id
    @personal_message.save!
    flash[:success] = "ok!"
    #redirect_to conversation_path(@conversation)
    redirect_to conversation_path(@conversation, user_id: current_user.id, receiver_id: @receiver)
  end