我正在尝试使用Rails实现与Twitter非常相似的直接消息传递功能,我想知道我在这里做错了什么。我试图限制用户关注的关注者和用户的直接消息传递,但我只能限制直接消息传递给关注者,但由于某种原因无法为用户关注的用户添加此功能。
这是相关代码:app/controllers/messages_controller.rb
class MessagesController < ApplicationController
before_action :signed_in_user
before_action :find_user_id, only: :create
def create
@message = current_user.messages.build(message_params)
@message.recipient_id = @recipient.id
if @message.save
flash[:success] = "You successfully sent a message to #{@message.recipient.username}!"
redirect_to messages_path
else
flash[:error] = "There was an error sending your message, try again!"
redirect_to messages_path
end
end
private
def message_params
params.require(:message).permit(:recipient_id, :content)
end
def find_user_id
username = params[:message][:recipient].downcase
@recipient = User.where('lower(username) = ?', username).first
if @recipient.nil?
flash[:error] = "Invalid username"
redirect_to messages_path
elsif @recipient.following?(current_user) == nil || @recipient.follower?(current_user) == nil
flash[:error] =
"You can only direct message followers or users you are following"
redirect_to messages_path
end
end
end
问题区域似乎是这行代码:
elsif @recipient.following?(current_user) == nil || @recipient.follower?(current_user) == nil
elsif @recipient.following?(current_user) == nil works properly, but the latter code doesn't. The code from those two lines are from: app/models/user.rb
def follower?(other_user)
relationships.find_by(follower_id: other_user.id)
end
def following?(other_user)
relationships.find_by(followed_id: other_user.id)
end
如果有人可以帮助我或建议对此问题进行一些可能的修复,我们将不胜感激。如果您需要更多信息来理解代码或解决问题,请不要犹豫!
以下是了解其背后数据模型的其他信息:
在db / migrate文件夹中:
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
end
end
同样在同一目录中:
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.integer :sender_id
t.integer :recipient_id
t.string :content
t.timestamps
end
add_index :messages, [:sender_id, :recipient_id, :content]
end
end
谢谢。