ruby on rails undefined方法

时间:2015-05-30 05:22:25

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

sharvil@sharvil:~/railstut/blog$ rails c

Loading development environment (Rails 4.2.1)
2.2.2 :001 > q=Question.all

  Question Load (0.5ms)  SELECT `questions`.* FROM `questions`
 => #<ActiveRecord::Relation [#<Question questions_id: 1, question: "What is this", almuni_almuni_id: 1, category_category_id: 1>]> 

2.2.2 :002 > q

 => #<ActiveRecord::Relation [#<Question questions_id: 1, question: "What is this", almuni_almuni_id: 1, category_category_id: 1>]> 

2.2.2 :003 > q.question

NoMethodError: undefined method `question' for #<Question::ActiveRecord_Relation:0x000000045dc178>
    from /home/sharvil/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/relation/delegation.rb:136:in `method_missing'

我在访问q.questions时遇到错误..问题是表格中的列。

请帮助。

2 个答案:

答案 0 :(得分:2)

你需要做 - q.first.question。您的q问题的集合,而不是Question的实例。你在问题集合上调用了question方法,这就是你得到错误的原因。

答案 1 :(得分:0)

在您的情况下 q 是问题收集

q.each do |que|
  puts que.question
end