alfa alfa - 2 years ago 86
Ruby Question

ActiveRecord_Associations_CollectionProxy:0x0000000e490b98 in RoR

I'm creating a application using ruby on rails, but currently i'm suffering a problem like db relation, below my code:


has_many :posts, :foreign_key => :company_id


belongs_to :companies, :foreign_key => :company_id


@post = current_user.companies.all


<% @post.each do |p| %>
<%= p.posts.post_title %>
<% end %>

Showing error above code.

If I
like use
<%= debug p.posts %>
then showing all posts, which is under my
but when I use
<%= debug p.posts.post_title %>
then showing


Answer Source

I think the problem here is that you are trying to call the method :post_title on p.posts, which is an ActiveRecord::Associations::CollectionProxy object.

In your example, p is a Company object, which has a method posts, which returns to you a CollectionProxy object that acts a lot like a list of posts. That list will not have a method post_title, but each element of that list will have a method post_title

So, instead of

<% @post.each do |p| %>
  <%= p.posts.post_title %>
<% end %>

You will want something like:

<% @post.each do |company| %>
  <% company.posts.each do |post| %>
    <%= post.post_title %>
  <% end %>
<% end %>

Two additional things to note:

1) The variable @post is inaccurately named. Inaccurate variable names will lead to confusion when trying to understand what is happening. current_user.companies.all returns a list of companies, and therefore, it should read:

@companies = current_user.companies.all


@post = current_user.companies.all

2) The actual error that is being shown to you likely says something like

Undefined Method 'post_title' for ActiveRecord_Associations_CollectionProxy:0x0000000e490b98

Not just


When debugging and asking for help, it's very important to note the entire message of the exception being raised.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download