answers_controller:
@questions = Question.order("qtype, position")
@ans = Answer.where(user_id = current_user.id)
@answers = @questions.map { |q| [q, @ans.find_by_question_id(q.id)] }
查看:
<%= form_for @answers, :remote => true do |form| %>
错误是因为 @answers 被映射了吗?如有任何帮助,我们将不胜感激。
更新:
答案模型:
belongs_to :user
belongs_to :question
用户模型:
has_many :answers
问题模型:
has_many :answers
更新2: 我将以下内容复制并粘贴到 Controller 中。
@answers = current_user.answers.questions
我得到以下信息:
undefined method `questions' for #<Class:0x1032d6d98>
我尝试采用第二种方法 - 用户模型:
has_many :answers, :through => :answers
Controller :
@questions = current_user.questions
得到:
undefined method `questions' for #<User:0x103569ec0>
app/controllers/answers_controller.rb:18:in `index'
最佳答案
是的,就是这个原因。您可能想做: current_user.answers.questions
如果您根据需要设置了关联,将准确返回您想要的内容(通过在幕后使用联接)
更新:
现在,通过查看您的关联,我不确定您想要实现什么目标。 @answers = current_user.answers 不会返回所有答案,然后在 View 中您可以使用答案和相应的问题(并且仍然使用 form_for @answers)。 但是,如果您想要@questions,您可以执行以下操作:
首先,将用户与问题关联起来
class User
has_many :questions, :through => :answers
end
Controller 中的:
@questions = current_user.questions
希望对您有所帮助。
关于ruby-on-rails - Rails 3 数组 :Class 的未定义方法 `model_name',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914736/