nil的未定义方法`username':通过关联添加has_many时的NilClass

时间:2017-06-27 04:24:10

标签: ruby-on-rails friendly-id

(编辑:见解决方案) 我有一个模型,目标,使用friendly_id。我已将其设置为向slug添加用户名,并且所有这些都很有效,直到我添加了has_many_through关联,以便用户可以参与目标。 我正在为nil获取一个未定义的方法'username':每当我尝试添加一个新目标时,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'

它说的控制器(目标#创建)给了我麻烦。

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模型的

,它会转移到其他错误消息,这就是我认为麻烦的地方。

2 个答案:

答案 0 :(得分:1)

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

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

您已定义has_many :goals两个,所以行

@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'

答案 1 :(得分:0)

您可以在候选人中引用方法:user_username。

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