第一次使用Ruby on Rails构建任何东西,而在实现“ has_many through”方面有些失落
在此应用中,我有问题,DailyQuestionSet(每天将有一个DailyQuestionSet)和DailyQuestions(多对多链接表,以便DailyQuestionSet可以有多个问题。
(我意识到这些表/模型名称不好,任何改进的建议都非常受欢迎:)
我陷入了在DailyQuestionSet应用程序上创建名为get_today_dailyquestionset的方法的步骤,该方法进入数据库以查看当天是否存在DailyQuestionSet,如果不存在,则创建一个并返回其值。 .questions属性填充了数据库中的所有问题。
(稍后,我将从将所有问题改为每天选择3个随机问题)
class Question < ApplicationRecord
has_many :dailyquestions, foreign_key: 'dailyquestion_id'
has_many :dailyquestionsets, :through => :dailyquestions
default_scope -> { order(created_at: :desc) }
end
class DailyQuestion < ApplicationRecord
belongs_to :daily_question_set
belongs_to :question
end
class DailyQuestionSet < ApplicationRecord
has_many :daily_questions, foreign_key: 'question_id'
has_many :questions, :through => :daily_questions, :source => :question
def self.get_today_dailyquestionset
@dailyquestionset_list = DailyQuestionSet.where('posed_date BETWEEN ? AND ?', DateTime.now.beginning_of_day, DateTime.now.end_of_day).all
if @dailyquestionset_list.count == 0
@dailyquestionset = DailyQuestionSet.new(posed_date: DateTime.now)
@dailyquestionset.save
end
@questionlist = Question.all
@questionlist.each do |q|
@dailyquestionset.questions << q
end
return @dailyquestionset_list[0]
end
end
我收到此错误,我认为这是从Question.all返回的Question对象没有与它们关联的DailyQuestionSet。有道理。但是我找不到在将每个问题添加到.questions数组之前为每个问题创建多对多关系的方法。
ERROR["test_create_daily_daily_question_set_if_not_already_existing", DailyQuestionSetTest, 1.0837379119993784]
test_create_daily_daily_question_set_if_not_already_existing#DailyQuestionSetTest (1.08s)
ActiveRecord::RecordInvalid: ActiveRecord::RecordInvalid: Validation failed: Daily question set must exist
app/models/daily_question_set.rb:20:in `block in get_today_dailyquestionset'
app/models/daily_question_set.rb:19:in `get_today_dailyquestionset'
test/models/daily_question_set_test.rb:11:in `block in <class:DailyQuestionSetTest>'
答案 0 :(得分:0)
是的,belongs_to验证关联是否存在。您应该添加可选:如果您不希望这样做,则为true
class DailyQuestion < ApplicationRecord
belongs_to :daily_question_set, optional: true
belongs_to :question, optional: true
end
https://github.com/rails/rails/issues/34454
您应该检查
@dailyquestionset.save
返回true,否则可能未通过验证。或使用保存!引发异常。
此外,如果@dailyquestionset_list.count > 0
,则@dailyquestionset
为零。
p.d .:很高兴为您提供更多信息 p.d.d:
中有一种类型 @dailyquestionset_list = DailyQuestionSet.where('posed_date BETWEEN ? AND ?', DateTime.now.beginning_of_day, DateTime.now.end_of_day).all
我认为应该是posted_dated
和
@dailyquestionset = DailyQuestionSet.new(posed_date: DateTime.now)
但这取决于架构。