gpt4 book ai didi

mysql - 两个应用程序共享同一个数据库 Rails

转载 作者:可可西里 更新时间:2023-11-01 07:27:34 24 4
gpt4 key购买 nike

不确定我是不是想多了,但希望得到一些关于这种情况的指导和建议。

我有两个应用程序,一个可以登录并执行基本的 CRUD,即创建博客文章,第二个是同一应用程序的 View ,但不能登录也不能创建博客文章。第二个应用程序将从与第一个相同的数据库中读取。

我的问题是如何让这两个应用程序从开发中的同一个模型读取数据,我是否仍然需要在仅查看应用程序中创建包含列等的模型?

例子

应用 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(无污垢)

class Post < ActiveRecord::Base
#do i still provide all associations and attributes here?
end

如果能解释一下这种设置中发生了什么,我将不胜感激

谢谢

最佳答案

您需要在两个应用程序之间共享或复制您的模型。这意味着 App 2 的 Post 示例需要具有关联、范围和方法。

我之前通过将所有模型类移动到包含在两个项目中的 gem 中完成了一次。这实际上很容易做到。

不过,您不需要需要共享迁移。如果它们指向同一个数据库,则迁移应该只存在于一个应用程序中,可能是编写程序的那个应用程序。我什至不会让 db/schema 在 App 2 上 checkin ,并且可能会更进一步并禁用 rake db:* 任务。

即使您将模型移动到共享 gem 中,您可能希望您的“只读”应用程序通过清除分配属性(attr_accessibleaccepts_nested_attributes_for ) 或以某种方式阻止 ActiveRecord 模型在其环境中保存。一种快速而肮脏的方法是在 App 2 的初始化程序中猴子修补 ActiveRecord::Base#save 并让它什么都不做或引发错误。

关于mysql - 两个应用程序共享同一个数据库 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21304320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com