nil的未定义方法`name':NilClass - 模型关联问题

时间:2016-07-07 23:54:20

标签: ruby-on-rails

我有一个User,Conversation和Message模型。用户有很多对话和消息。 Conversation has_many消息,消息属于用户和对话。对话和消息模型都有一个user_id列。

当我尝试显示与特定消息关联的用户名时,我得到了未定义的方法错误。

My Conversations_controller

 class ConversationsController < ApplicationController
  def create
    @conversation = current_user.conversations.build(conversation_params)
    if @conversation.save
      save_conversation(@conversation)
      flash[:notice] = "Conversation was succesfully created"
      redirect_to conversation_path(@conversation)
    else
      render 'new'
    end
  end

  def show
    @conversation = Conversation.find(params[:id])
    save_conversation(@conversation)
    @message = @conversation.messages.build
  end

我的消息控制器

class MessagesController < ApplicationController

  def create
    @message = current_conversation.messages.build(message_params)
    if @message.save
      flash[:notice] = "Message was successfully created"
      redirect_to conversation_path(current_conversation)
    else
      flash[:notice] = "Message not saved"
      render 'new'
    end
  end

  private

     def message_params
       params.require(:message).permit(:chat, :user_id)
     end

end

我的模特

class User < ApplicationRecord
  has_many :conversations
  has_many :messages
end
class Message < ApplicationRecord
  belongs_to :conversation
  belongs_to :user
end
class Conversation < ApplicationRecord
  belongs_to :user
  has_many :messages, dependent: :destroy
end

我的谈话显示了视图

<h1><%= @conversation.title %></h1>

<p>
  Description: <%= @conversation.description %>
</p>
<p>
    Created by: <%= @conversation.user.name %>
</p>

<% if @conversation.messages.any? %>
    <% @conversation.messages.each do |message| %>
      <%= message.chat %>
      <%= message.user.name %>

    <% end %>
  <% end %>

它的message.user.name,Rails似乎异常。我的印象是因为这两个模型是关联的,我可以使用user.name?

我非常感谢任何人提供的任何帮助,如果您需要其他任何帮助,请告诉我。

由于

1 个答案:

答案 0 :(得分:0)

这可能是因为:

您没有在消息模型

上验证用户的存在

您可能没有在messages_controller中分配user_id的值,我可能遵循的方法是:

class MessagesController < ApplicationController
  def create
    @message = current_conversation.messages.build(message_params)
    @message.user = current_user # provided you have current_user set somewher
    if @message.save
      flash[:notice] = "Message was successfully created"
      redirect_to conversation_path(current_conversation)
    else
      flash[:notice] = "Message not saved"
      render 'new'
    end
  end
  ...
end