我想创建一个新的“AnswerStat”对象并将其保存在数据库中。我正进入(状态:
can't write unknown attribute `answer_stat_id'
app/models/answer_stat.rb:14:in `new'
app/models/answer_stat.rb:14:in `add_answer'
app/controllers/users_controller.rb:31:in `block in index'
app/controllers/users_controller.rb:30:in `each'
answer_stat_id 不存在,我猜它是指表 answer_stats 的主键,即 id。我当然没有明确声明这个属性。为什么 Rails 会寻找这个不存在的属性?代码:
class AnswerStat < ActiveRecord::Base
attr_accessible :contact, :statement, :answer_sum, :answer_count, :variation
belongs_to :contact, :class_name => "Friend"
has_one :statement
validates_uniqueness_of :contact, :scope => :statement
def self.add_answer(answer)
if stat = AnswerStat.find_by_contact_id_and_statement_id(answer.contact.id, answer.statement.id)
...........do some stuff...........
else
@answer_stat = AnswerStat.new(:contact => answer.contact, :statement => answer.statement, :answer_count => 1, :answer_sum => answer.description, :variation => answer.description)
@answer_stat.save
end
end
我从 rails 控制台或任何控制器调用它,使用:
Answer.all.each do |a|
AnswerStat.add_answer(a)
end
answer_stats 表(使用 PRAGME table_info(answer_stats) 的 sqlite3):
0|id|INTEGER|1||1
1|contact_id|integer|0||0
2|answer_sum|integer|0||0
3|answer_count|integer|0||0
4|created_at|datetime|1||0
5|updated_at|datetime|1||0
6|statement_id|integer|0||0
7|variation|integer|0||0
提前致谢