簡體   English   中英

如何將ActiveRecord :: Associations擴展到rails中的Frozen_record

[英]How can I extend ActiveRecord::Associations to a frozen_record in rails

我在Rails中使用“ 凍結記錄” gem上傳了一個YAML文件,其中包含有關我的應用程序的一些固定問題。 上載它們之后,我想使用SaleQualifier模型來抓取每個問題,將其與答案相關聯,然后將其用作狀態機來遍歷問題樹。

我的Frozen Record gem可以正常工作了,YAML文件上傳就很好了。 當我嘗試將模型與新模型(SaleQualifier)相關聯時,出現'method_missing': undefined method 'belongs_to' for Question:Class (NoMethodError)

結果,我添加了include ActiveRecord :: Associations組件,以使我可以將新記錄與我的SaleQualifier Question belongs_to :sale_qualifier -但這會引發:

'method_missing': undefined method 'dangerous_attribute_method?' for Question:Class (NoMethodError)

根據我的搜索,當我事先聲明該方法時,將引發此錯誤。 我不知道它的定義位置,但是從Frozen_Record gem文件中,我可以看到它們使用以下內容設置了FrozenRecord

module FrozenRecord
 class Base
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::AttributeMethods
  include ActiveModel::Serializers::JSON
  include ActiveModel::Serializers::Xml
 end
end

我開始認為使用此gem可能會過大,也許我應該將問題加載到正常的ActiveRecord::Base模型中,但是我喜歡FrozenRecord的想法,因為這正是我要實現的目標。

我的代碼:

class Question < FrozenRecord::Base
 include ActiveModel::Validations
 include ActiveRecord::Associations
 validates :next_question_id_yes, :question_text, :answer_type, presence: true
 belongs_to :sale_qualifier
 self.base_path = 'config/initializers/'
end

銷售資格:

class SaleQualifier < ActiveRecord::Base
 has_many :questions
end

有人可以幫我解開我似乎自己陷入的混亂嗎? 也許我應該只是從FrozenRecord中挖掘出YAML上傳功能,然后將它們轉儲到我的Question模型中而不使用gem。

因此,最終,Frozen_Record似乎並沒有真正增加我的應用程序。 給定文件是從YAML加載的,並且沒有控制器,我想沒有辦法更新Question記錄,除非有人已經破壞了我的數據庫並插入了自己的questions.yml文件。

因此,我只是如下更改了Question模型,以加載YAML並將其作為新Question記錄插入數據庫中:

class Question < ActiveRecord::Base
 validates :next_question_id_yes, :question_text, :answer_type, presence: true
 belongs_to :sale_qualifier

 File.open("#{Rails.root}/config/initializers/questions.yml", 'r') do |file|
   YAML::load(file).each do |record|
      Question.create(record)
   end
 end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM