ruby-on-railsmodel-associations

Rails: attr_accessor association


Hello I am beginner for rails.

I have two models UserSubscriptions and SubscriptionPlan.

user_subscription.rb

class  UserSubscription < ApplicationRecord
  attr_accessor :new_plan_id
 
  belongs_to :subscription_plan
  belongs_to :new_plan_id, class_name: 'SubscriptionPlan', foreign_key: :new_plan_id
end

subscription_plan.rb

class SubscriptionPlan < ApplicationRecord
  has_many :user_subscriptions
end

I want to get new_plan as an object of subscription_plan model. Still I am unable to get this. Plz help.

Thank you in advance.


Solution

  • You never want to use attr_accessor in Rails models.*

    attr_accessor is used in plain old ruby objects to generate accessor methods for instance variables. If you use attr_accessor in a Rails model you're clobbering the setter and getter that it creates from reading the database schema.

    The result is that the attribute will not be persisted when you save. This is because the attrbute is not stored in the attributes hash and is not marked as dirty. It also won't be included in any of the methods that use the attributes api such as #attributes or #to_json.

    It will also break the association as well.

    class  UserSubscription < ApplicationRecord
      belongs_to :subscription_plan
      belongs_to :new_plan, class_name: 'SubscriptionPlan'
    end