我的Rails应用程序中有一个独立的问题模型,其中的问题是通过YAML加载的。我找到了正确的问题,并通过创建SaleQualifier(有一个question_id字段)将其加载到视图中,但我没有声明关联(例如SaleQualifier has_one问题),因为这会破坏网站的其他部分。
现在我想在我的应用程序中找到SaleQualifiers,具体取决于SaleQualifier和Question模型中的字段 - 我正在尝试编写正确的SQL查询,以便我可以检索记录。任何人都可以帮助我理解如何有效地编写这个,因为这是我第一次尝试编写自己的SQL命令。
我的架构:
create_table "questions", force: true do |t|
t.text "question_text"
t.string "answer_type"
t.integer "next_question_id_yes"
t.integer "next_question_id_no"
t.datetime "created_at"
t.datetime "updated_at"
t.string "sale_stage"
t.boolean "collectable", default: false
end
create_table "sale_qualifiers", force: true do |t|
t.integer "question_id"
t.integer "next_question_id", default: 1
t.datetime "created_at"
t.datetime "updated_at"
t.integer "sales_opportunity_id"
t.boolean "has_answer", default: false
t.integer "prior_question_id", default: 1
t.integer "collection_id"
end
我的问题.rb:
class Question < ActiveRecord::Base
validates :next_question_id_yes, :question_text, :answer_type, presence: true
File.open("#{Rails.root}/config/initializers/questions.yml", 'r') do |file|
YAML::load(file).each do |record|
Question.create(record) unless Question.exists?(record)
end
end
end
SaleQualifier.rb:
class SaleQualifier < ActiveRecord::Base
has_one :answer, :inverse_of => :sale_qualifier, dependent: :destroy
accepts_nested_attributes_for :answer
belongs_to :sales_opportunity
validates :sales_opportunity_id, presence: true
validates_associated :answer
after_save :update_sales_opp_question
end
一个示例问题:
- id: 1
question_text: Why does this company need to buy your products or services?
answer_type: Text Field
next_question_id_yes: 2
next_question_id_no: ~
collectable: ~
sale_stage: Prospecting
我想要实现的是找到属于sales_opportunity的所有SaleQualifiers,has_answer:'true',并且问题sale_stage是Prospecting。
我尝试了什么:
SaleQualifier.find_by_sql("SELECT * FROM sale_qualifiers WHERE sales_opportunity_id = '83' has_answer = 'true' INNER JOIN questions ON questions.id = sale_qualifiers.question_id ORDER question.id desc")
导致以下错误:
SaleQualifier Load (15.8ms) SELECT * FROM sale_qualifiers INECT * FROM sale_qualifiers WHERE sales_opportunity_id = '83' has_answer = 'true' INNER JOIN questions ON questions.id = sale_qualifiers.question_id ORDER question.id desc
PG::Error: ERROR: syntax error at or near "*"
LINE 1: SELECT * FROM sale_qualifiers INECT * FROM sale_qualifiers W...
有人可以帮我理解如何写这个查询吗?
答案 0 :(得分:0)
试
SaleQualifier.find_by_sql("SELECT sale_qualifiers.* FROM sale_qualifiers WHERE sales_opportunity_id = '83' has_answer = 'true' INNER JOIN questions ON questions.id = sale_qualifiers.question_id ORDER question.id desc")