ruby - ActiveRecord query to join Posts, post authors and likes in Rails 4 -
so, have read through quite few rails active records pages, stack o questions , answers (about 12 hours of time) trying figure out how heck tie of these things single query display them on page.
here page view
secrets owner info </h3> <% @secretinfo.each |i| %> <p><%= i.content %> - <%= i.first_name %></p> <p><%= i.created_at %></p> --> "this i'd have likes post" <-- <% end %>
and here 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 see models , schema here those
class user < activerecord::base attr_accessor :password has_many :gossips has_many :likes has_many :liked_secrets, :through => :gossips, :source => :gossip class < 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 seems impossible or simple overlooking. easy in php/mysql. appreciated.
additional points coming query allows me see posts user has created , liked!
well, want eager loading: load data associated record in single roundtrip database. example, think can load data this:
@user = user.where(id: params[:id]) .joins(:liked_secrets) .includes(:liked_secrets => :likes) .first! @secretinfo = @user.liked_secrets.map |secret| openstruct.new( content: secret.content, first_name: user.first_name, created_at: secret.created_at, likes: secret.likes ) end
this works including in data fetched database in first query data associated included in include
parameter. so, calling @user.liked_secrets
return secrets won't call database because information came database in first query. same happens if @user.liked_secrets.first.likes
because of :linked_secrets => :likes
parameter on initial query.
i'll let link blog post here: http://blog.arkency.com/2013/12/rails4-preloading/.
and, if feel rails orm (activerecord) doesn't works use case, can use sql in string or fallback use ruby orm out there (like sequel).
Comments
Post a Comment