[英]Rails: attr_accessor association
Hello I am beginner for rails.你好,我是rails的初学者。
I have two models UserSubscriptions
and SubscriptionPlan
.我有两个模型
UserSubscriptions
和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.我想将
new_plan
作为subscription_plan
计划 model 的 object 获得。 Still I am unable to get this.我仍然无法得到这个。 Plz help.
请帮忙。
Thank you in advance.先感谢您。
You never want to use attr_accessor
in Rails models.*你永远不想在 Rails 模型中使用
attr_accessor
。*
attr_accessor
is used in plain old ruby objects to generate accessor methods for instance variables. attr_accessor
在普通的旧 ruby 对象中用于生成实例变量的访问器方法。 If you use attr_accessor
in a Rails model you're clobbering the setter and getter that it creates from reading the database schema.如果您在 Rails model 中使用
attr_accessor
,那么您正在破坏它通过读取数据库模式创建的 setter 和 getter。
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.
这是因为属性没有存储在属性 hash 中,并且没有标记为脏。 It also won't be included in any of the methods that use the attributes api such as
#attributes
or #to_json
.它也不会包含在任何使用属性 api 的方法中,例如
#attributes
或#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.