Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails error:AssociationRelation is not an ActiveModel-compatible object. It must implement :to_partial_path

I have the following view:

# index.html.web
<h1>Listing answers</h1>

<%= will_paginate %>

  <%= render [@answers]%>

<%= will_paginate %>

And the following index action:

def index
  @question = Question.find(params[:question_id])
  @answers = @question.answers.paginate(page: params[:page])
  respond_with(@answers)
end

I'm getting the following errror:

ActiveRecord::AssociationRelation [#<Answer id: 2, content: "b", user_id: nil, question_id: 1, created_at: "2015-04-27 14:59:32", updated_at: "2015-04-27 14:59:32">, #<Answer id: 3, content: "d", user_id: 1, question_id: 1, created_at: "2015-04-27 15:15:01", updated_at: "2015-04-27 15:15:01"] is not an ActiveModel-compatible object. It must implement :to_partial_path.

How can I fix it?

like image 432
voxter Avatar asked Oct 29 '25 18:10

voxter


2 Answers

You can do it in two different ways.

<%= render @answers %>  OR  
<%= render partial: 'answer', collection: @answers %>

In both cases, you will get an object named answer in partial view.

And you must have a file named _answer.html.erb should exists in same directory.

like image 193
Sarwan Kumar Avatar answered Oct 31 '25 09:10

Sarwan Kumar


When you pass a collection of instances to render the partial, you don't need to put any square bracket around the instance.

<%= render @answers %>

And don't forget to create a view name _answer.html.erb as well

source: http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables

like image 32
mininoz Avatar answered Oct 31 '25 07:10

mininoz