jeudi 15 décembre 2016

Rails: Cannot access column from a join-table in a partial

I want to access a column from a join-table in a partial. When I access this column in a "normal" view (e.g. fakeposts#index) it is working, however if I want to do the same in a partial, it does not work.

Example:

I have a users and a fakeposts table. For each user I want to display the fakeposts in a specific (randomized) order - namely based on a randomized_time column -, which is saved in a join table:

randomized_posts table:

user_id | fakepost_id | randomized_time

My Models look like this:

#user.rb
has_many :randomized_posts

#fakepost.rb
has_many :randomized_posts

# randomized_post.rb
belongs_to :fakepost
belongs_to :user

In my fakepost_controller.rb I want to get the fakeposts for the current_user and add the column "randomized_time" to my selection:

My fakepost_controller.rb

def index
  @fakeposts = Fakepost.joins(randomized_fakeposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")
end

This is working: index.html.erb

<% @fakeposts.each do |post| %>
   <%= post.randomized_time %>
<% end %>

This is not working: index.html.erb and my partial

#index.html.erb
<% @fakeposts.each do |post| %>
   <%= render :partial => "layouts/individual-post", :locals => {:post => post} %>
<% end %>

#layouts/_individual-post.html.erb
<%= post.randomized_time %>

However, something like <%= post.created_at %> is working fine in my partial so I guess calling my partial is correct?

Aucun commentaire:

Enregistrer un commentaire