ruby将参数传递给内部方法

时间:2017-03-21 15:13:10

标签: ruby ruby-on-rails-5

我是编程的新手,我正在做轨道。我有一个红宝石问题。

我有一个方法对应方,它将消息和对话作为参数

    def counterpart(message, conversation)
        if  message.author_id == conversation.sender_id
          counterpart_id = conversation.receiver_id
        else
          counterpart_id = conversation.sender_id
        end
    end

并且在下面的方法create_notification中,我想在其中调用对应方法来获取变量counterpart_id。但是我怎样才能将参数消息和对话传递给对方呢?

    def create_notification(message, conversation)
        counterpart(message, conversation)
        notification = message.create_notification(
                  notifier_id: message.author_id,
                  receiver_id: counterpart_id,
                  content: "#{message.author.name} sent you a message",
                  title: "message")
    end

感谢

1 个答案:

答案 0 :(得分:0)

我们对您的模型知之甚少。因此,据我所知,使代码正常工作的最佳方法是转移到

def counterpart(message, conversation)
  message.author_id == conversation.sender_id ? conversation.receiver_id : conversation.sender_id
end

def create_notification(message, conversation)
  message.create_notification(notifier_id: message.author_id,
      receiver_id: counterpart(message, conversation),
      content: "#{message.author.name} sent you a message",
      title: "message")
end