开发者

Rails Associations Help

I have a Users model which has many Projects. But each Project are of different types. A WebApplication, DesktopApplication and so on. All these different types have their own specific fields and yet they share common fields which wi开发者_运维技巧ll be stored in the Projects table.

I have thought of this solution having multiple has_one to each of the Project types in the project model. Is this the way to go?


Your best bet is probably one User to many Projects, then have an "extended info" that's polymorphically associated. I think that an example would describe better than that sentence.

class User < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :user
  has_one :project_type, :as => :type
end

class ProjectType < ActiveRecord::Base
  belongs_to :type, :polymorphic => true
end

class WebApplication < ProjectType
  # fields here
end

class DesktopApplication < ProjectType
  # fields here
end

@project.type = WebApplication.new
@otherproject.type = DesktopApplication.new

Unfortunately I can't test this to guarantee that it works, but I think I got everything correct :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜