使用Rails gem' Mailboxer'而sender_id始终为零

时间:2016-03-20 02:14:59

标签: ruby-on-rails ruby-on-rails-4 rubygems mailboxer

刚刚集成了Mailboxer,我遇到了一个问题。当我发送新邮件时,sender_id表中的mailboxer_notifications始终为零,而不是发件人的ID。

我使用了friendly_id gem作为用户名,我认为这就是问题所在,但我无法找到解决方法(如果问题就是这样)。

消息/ new.html.erb

<% provide(:title, "New Message") %>

<%= form_tag user_messages_path, method: :post do %>

  <div class="form-group">
    <%= label_tag 'message[subject]', 'Subject' %>
    <%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>
  </div>

  <div class="form-group">
    <%= label_tag 'message[body]', 'Message' %>
    <%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>
  </div>


<div class="form-group">
  <%= label_tag 'recipients', 'Choose recipients' %>
  <%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>
</div>

  <%= submit_tag 'Send', class: 'btn btn-primary' %>
<% end %>

messages_controller.rb

class MessagesController < ApplicationController
  before_action :authenticate_user

  def new
    @user = current_user
    @chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
  end

  def create
    @user = current_user
    recipients = User.where(id: params['recipients'])
    conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation
    flash[:success] = "Message has been sent!"
    redirect_to user_conversation_path(@user, conversation)
  end

  private

  def authenticate_user
    unless ((current_user.id = params[:user_id]) unless current_user.nil?)
      flash[:error] = 'Looks like your not supposed to be there'
      redirect_to login_path
    end
  end
end

的routes.rb

resources :users do
  resources :conversations, only: [:index, :show, :destroy] do
    member do
      post :reply
      post :restore
      delete :empty_trash
      post :mark_as_read
    end
  end
  resources :messages, only: [:new, :create]
end

在整合宝石时,我大部分都遵循this tutorial。我不知道为什么在发送新邮件时没有正确保存用户ID。

更新 我怀疑friendly_id导致它的原因是将sender_id保存为0是因为当我不在网址中使用友好ID时,例如users / 1 / messages / new它运行正常但是用户/ example-user / messages / new它在创建新消息时没有保存用户ID

1 个答案:

答案 0 :(得分:0)

我不确定是否遵循authenticate_user实施:

def authenticate_user
  unless ((current_user.id = params[:user_id]) unless current_user.nil?)
    flash[:error] = 'Looks like your not supposed to be there'
    redirect_to login_path
  end
end

您可能希望简化它。

如果您要将current_user.idparams[:user_id]进行比较,则需要使用current_user.id == params[:user_id],而不是current_user.id = params[:user_id]。它是==,而不是=