我試圖用find_or_initialize_by但是它不分配屬性,因爲它應該做的。我有以下幾點:紅寶石 - find_or_intialize_by未分配的屬性
vote_id = 1534
vote = record.answer_records.find_or_initialize_by(stage_answer_id: vote_id)
當我進入binding.pry我可以看到以下:
vote
=> #<AnswerRecord id: 3926, stage_record_id: 2210, stage_answer_id: nil, value: "{:stage_answer_id=>1563}", correct: false, created_at: "2017-09-06 11:33:49", updated_at: "2017-09-06 11:33:49", deleted_at: nil>
出於某種原因,它被分配
value: "{:stage_answer_id=>1563}"
而非
stage_answer_id: 1563
我在做什麼錯?在此先感謝
編輯:answer_record.rb
class AnswerRecord < ActiveRecord::Base
acts_as_paranoid
belongs_to :stage_record
belongs_to :stage_answer
has_one :activity_feedback
def self.for_answer(answer)
find_by(stage_answer: answer)
end
def wrong?
!correct
end
end
第二個編輯: 從byebug更多:
>> opinion
=> #<AnswerRecord id: nil, stage_record_id: nil, stage_answer_id: 1692, value: "This is my answer", correct: true, created_at: nil, updated_at: nil, deleted_at: nil>
>> opinion.save
!! #<ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "value" violates not-null constraint
DETAIL: Failing row contains (3938, 2222, 1692, null, f, 2017-09-06 12:03:09.851213, 2017-09-06 12:03:09.851213, null).
: INSERT INTO "answer_records" ("stage_answer_id", "stage_record_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id">
由於日誌顯示PSQL試圖更新其他屬性,而不是「值'屬性,並且我沒有任何啓動器設置..
第三編輯:
show-method record.answer_records.find_or_initialize_by
返回以下
From: /Users/mark/.rvm/gems/ruby-2.3.2/gems/activerecord-4.2.7.1/lib/active_record/relation.rb @ line 223:
13:15:53 web.1 | Owner: ActiveRecord::Relation
13:15:53 web.1 | Visibility: public
13:15:53 web.1 | Number of lines: 3
13:15:53 web.1 |
13:15:53 web.1 | def find_or_initialize_by(attributes, &block)
13:15:53 web.1 | find_by(attributes) || new(attributes, &block)
13:15:53 web.1 | end
你是否重寫了'initialize'方法?這不是正常的行爲。 –
不是我的知識.. – Mark
等等,等等,我只是注意到了一些東西。在你的帖子的頂部,你寫道:'AnswerRecord id:3926' - 記錄**已經存在**!你有**找到它;沒有初始化它。 (所以'價值'是*沒有被分配*它已經在那裏。)這就是造成混亂的原因。 –