samedi 13 juin 2015

ActiveRecord query to join Posts, post authors and likes in Rails 4

So, I have read through quite a few rails active records pages, stack O questions and answers (about 12 hours of time) trying to figure out how the heck to tie all of these things together into a single query to display them on my page.

Here is my page view

Secrets with owner info
                        </h3>
                        <% @secretInfo.each do |i| %>
                                <p><%= i.content %> - <%= i.first_name %></p>
                                <p><%= i.created_at %></p>
                                --> "this is where I'd like to have likes for post" <--
                        <% end %>

and here is my controller

def show
        @user = User.find(params[:id])
    @secrets = Gossip.all
    @mySecrets = Gossip.where(user_id: [params[:id]])
    @secretInfo = Gossip.joins(:user).select("content", "first_name", "created_at")
    @secretWLikesNInfo = WTF MATE?
  end

Also, may help to see my models and schema so here are those

class User < ActiveRecord::Base
  attr_accessor :password
  has_many :gossips
  has_many :likes
  has_many :liked_secrets, :through => :gossips, :source => :gossip


class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :gossip
                               
class Gossip < ActiveRecord::Base
  belongs_to :user
  has_many :likes
  has_many :liking_users, :through => :likes, :source => :user                           

I don't know why this seems so impossible or it could be something very simple that I am just overlooking. This all was very easy in PHP/MySQL. All help is appreciated.

Additional points for coming up with a query that allows me to see all posts that I as a user has created AND liked!

Aucun commentaire:

Enregistrer un commentaire