כיצד אוכל להוסיף מאפיין למודל המשתמש?

סיכום מבוסס בינה מלאכותית

Alienazk is trying to add an attribute to the User model in a Discourse plugin by linking it to a custom table (“total_points”) and accessing its column “total_earned_points”. Their initial code fails with a nil error, likely because total_point is not properly initialized or accessed. They attempted to fix it by switching from self.total_point[:total_earned_points] to self.total_point.read_attribute(:total_earned_points) in post 4, but the issue persists. pfaffman suggests checking if an expected array is nil and recommends reviewing existing plugins like discourse-calendar or the all-the-plugins repo for working examples of similar patterns. Alienazk clarifies they simply want to expose a column from a new table as an attribute on the User model. The core problem appears to be improper association or attribute access in the add_to_class block, possibly due to the total_point association not being correctly defined or loaded.

I am trying to modify a plugin.
The following code failed and threw an error like:

#  total_points is a sum table with column "total_earned_points".
module MyModel::UserExtension
  def self.prepended(base)
    base.has_many :user_points, class_name: 'MyModel::UserPoint'
    base.has_one :total_point, class_name: 'MyModel::TotalPoint'
  end
end
 reloadable_patch do |plugin|
    User.class_eval { prepend MyModel::UserExtension }
  end

 add_to_class(:user, :total_earned_points) do
    # self.user_points.sum(:reward_points)
    self.total_point[:total_earned_points]
  end

I am very new to rails. Could you please tell me what is wrong with it?
Thanks so much!

Sorry this might not be much help, but it’s fast. :slight_smile:

Something that you expect to be an array is nil. Mabye args is nil and needs to be a []?

You can also take a look at GitHub - discourse/all-the-plugins · GitHub to try to find examples of what you’re trying to do (I can’t quite tell what you’re trying to do).

Check out discourse-calendar. It adds an Event class, which seems pretty analogous to what you’re trying to do.

There are a bunch of plugins taht have a similar reloadable_patch block, though.

Thank you for reply!
I just create a new table and want to add one of the columns of the table to user table.

I change

add_to_class(:user, :total_earned_points) do
    # self.user_points.sum(:reward_points)
    self.total_point[:total_earned_points]
end

to

add_to_class(:user, :total_earned_points) do
    # self.user_points.sum(:reward_points)
    self.total_point.read_attribute(:total_earned_points)
end

still doesn’t work. :cold_sweat:
Can anyone help me?