通过关联添加 has_many 时 nil:NilClass 的未定义方法“用户名”

undefined method `username' for nil:NilClass when adding has_many through association

(编辑:查看包含的解决方案) 我有一个模型 Goal,它使用 friendly_id。我已将其设置为将用户名添加到 slug,并且一切正常,直到我添加了一个 has_many_through 关联以便用户可以参与目标。 每当我现在尝试添加新目标时,我都会收到一个未定义的方法 'username' for nil:NilClass 错误:

def slug_candidates
    [
      [user.username, :title]
    ]
  end

这是我的模型,goal.rb:

class Goal < ApplicationRecord

  belongs_to :user
  has_many :participations
  has_many :users, through: :participations

  # Solution 
  has_many :participations, dependent: :destroy
  has_many :participants, :through => :participations, :source => :user

  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged
  delegate :username, to: :user, prefix: true

  def slug_candidates
    [
      [user.username, :title]
    ]
  end

  def should_generate_new_friendly_id?
    slug.blank? || title_changed?
  end
...

user.rb

class User < ApplicationRecord      
  extend FriendlyId
  friendly_id :username, use: :slugged

  validates :username, presence: true, length: { minimum: 4, maximum: 16 } 
  validates_uniqueness_of :username

  has_many :goals, dependent: :destroy
  has_many :participations, dependent: :destroy
  has_many :goals, through: :participations, source: :goal

  # Solution
  has_many :participations, dependent: :destroy
  has_many :participant_goals, through: :participations, :source => :goal

我也试过使用

  has_many :participations, dependent: :destroy
  has_many :goals, through: :participations, class_name: 'Goal'

它说的控制器 (Goal#create) 给我带来了麻烦。

def create
    @goal = current_user.goals.build(goal_params)

    respond_to do |format|
      if @goal.save
        format.html { redirect_to @goal, notice: 'New goal saved successfully!' }
      else
        format.html { render :new }
      end
    end
  end

参与模型如下:

class Participation < ApplicationRecord
  belongs_to :user
  belongs_to :goal
  validates :user_id, presence: true
  validates :goal_id, presence: true
end

我感觉它与新协会有关,但我不知道如何解决它。如果我删除

has_many :participations, dependent: :destroy
has_many :goals, through: :participations, source: :goal

从 user.rb 模型开始,它继续显示其他错误消息,所以我认为这就是问题所在。

可以参考考生中的方法:user_username

def slug_candidates
  [
    [:user_username, :title]
  ]
end

这是用户模型中的问题...

has_many :goals, dependent: :destroy
has_many :participations, dependent: :destroy
has_many :goals, through: :participations, source: :goal

您已经定义了has_many :goals twoice,所以行

@goal = current_user.goals.build(goal_params)

未正确构建 @goal 对象。

试试这个...

has_many :goals, dependent: :destroy
has_many :participations, dependent: :destroy
has_many :participants_goals, through: :participations, class_name: 'Goal'