开发者

Mapped array error in Rails 3

开发者 https://www.devze.com 2023-03-03 13:40 出处:网络
I\'ve spent 3 days trying to write scopes in models. At this point i don\'t care about producing the optimum solution... i just want to get this to work. In a rails 3 app i have the following code in

I've spent 3 days trying to write scopes in models. At this point i don't care about producing the optimum solution... i just want to get this to work. In a rails 3 app i have the following code in the controller.

@questions = Question.all
@ans = Answer.where(user_id = current_user.id)
@answers = @questions.map { |q| [q, @ans.find_by_question_id(q.id)] }

Each answer record has a question_id field so it can be linked to the appropriate question. I am trying to get the answers array to list out in the same order as the questions.

The following code in a view renders the answers but not in the correct order.

<% @ans.each do |q| %>
  <%=q.score%><br/>
<% end %>

I then changed the array to the mapped array which should produce the answers in the appropriate order.

<% @answers.each do |q| %>
  <%=q.score%><br/>
<% end %>

I get the following error:

undefined method `score' for #<Array:0x1033开发者_开发问答5ef90>

Any help is appreciated. Thanks.


Instead of q.score you probably want q[1].score, since q is really a two-item array of the question and answer. The second item (q[1]) will give you the answer.


This is because q is not an Answer, but an array containing both a Question and an Answer. So you could just change it to q[1].score. A nicer way is to break out the array in the block variables, like so (note the parentheses):

<% @answers.each do |(question, answer)| %>
  <%= answer.score %><br/>
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消