用户只能有两种类型的订阅:DailySubscription和WeeklySubscription。当用户处于新的编辑操作时,我希望他们检查他们想要获得的任何订阅。
我很喜欢使用嵌套字段(根据Ryan Bates的截屏视频here)但我认为当我添加继承时,它确实使事情变得复杂。 有更好的方法吗?
class User < ActiveRecord::Base
has_many :subscriptions
end
class Subscription < ActiveRecord::Base
belongs_to :user
# type field is defined in the migration for Single Table Inheritance
end
class DailySubscription < Subscription
# Business logic here
end
class WeeklySubscription < Subscription
# Different business logic here
end
我对控制器的初步努力是古怪的:
class UsersController < ApplicationController
def new
@user = User.new
# I can't use @user. subscriptions.build as Rails doesn't
# know what type of model to add!
@user.subscriptions = [DailySubscription.new, WeeklySubscription.new]
end
...
end
我认为我在概念上确实错过了一些东西,但我无法弄明白。救命啊!
答案 0 :(得分:0)
根据您的描述,您的用户只有两种可能的订阅选择:每日和/或每周。因此,你不需要有一个has_many关联,因为两个has_one就足够了(注意下面的多态可订阅:
class User < ActiveRecord::Base
has_one :daily_subscription, :as => :subscribeable
has_one :weekly_subscription, :as => :subscribeable
end
class Subscription < ActiveRecord::Base
belongs_to :subscribeable, :polymorphic => true
# type field is defined in the migration for Single Table Inheritance
end
class DailySubscription < Subscription
# Business logic here
end
class WeeklySubscription < Subscription
# Different business logic here
end
此外,对于控制器,您只需要初始化User。初始化时,@ user.daily_subscription和weekly_subscription将为.blank确定为null?方法。当您继续在create方法中创建用户时,您需要使用相应订阅的实例填充这些字段。
class UsersController < ApplicationController
def new
@user = User.new
# bam -- youre done.
end
...
端