我想创建一个新的“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
提前致谢
答案 0 :(得分:2)
它可能来自statement
属性,它引用了一个关联的模型。我认为语句表中有it's looking for an answer_stat_id foreign key。
你应该:
@answer_stat.build_statement(...)