不确定我是否过度思考这个问题,但希望能对这种情况提供一些指导和建议.
我有两个应用程序,一个可以登录并执行基本的CRUD,即创建博客帖子,第二个是相同应用程序的视图,但无法登录,也无法创建博客文章.第二个应用程序将从与第一个相同的数据库中读取.
我的问题是如何让两个应用程序在开发中从同一个模型中读取,我是否还需要在仅视图应用程序中创建带有列等的模型?
例
应用1(使用CRUD)
class Post < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :category
belongs_to :user
has_many :images, as: :imageable, :dependent => :destroy
accepts_nested_attributes_for :images
attr_accessible :comments, :title, :category_id, :user_id, :image_id, :images_attributes, :imageable_id, :imageable_attributes, :slug
#Validations
validates :comments, :presence => {:message => 'Add your Comments'}
validates :title, :presence => {:message => 'Add your Title'}
#scopes
scope :latest_posts, :order => "posts.created_at DESC"
#scope :ruby_posts, :include => :category, :conditions => {"categories.name" => "Ruby"}, :order => "posts.created_at DESC"
def self.search(search)
where("title like ?", "%#{search}%")
end
end
应用2(无Crud)
class Post < ActiveRecord::Base
#do i still provide all associations and attributes here?
end
我真的很感激这种设置的解释
谢谢
解决方法:
您需要在两个应用程序之间共享或复制模型.这意味着App 2的Post示例需要具有关联,范围和方法.
之前我已经将所有模型类移动到包含在两个项目中的gem中.这实际上很容易做到.
您不需要共享迁移.如果他们指向同一个数据库,那么迁移应该只存在于一个应用程序中,可能就是写作的应用程序.我甚至不会在App 2上签入db / schema,并且可能会进一步禁用rake db:* tasks.
即使您将模型移动到共享gem中,您也可能希望“只读”应用程序通过清除分配属性(attr_accessible和accepts_nested_attributes_for)的权限或以某种方式阻止ActiveRecord模型在其环境中保存来强制执行其只读行为.一种快速而肮脏的方法是在App 2的初始化程序中修补ActiveRecord :: Base#save,并使其无效或引发错误.