![](/img/trans.png)
[英]How to access published attributes of pubnub from view in Ruby on rails
[英]ruby on rails how to access left join variables from view
我的索引控制器:
class IndexController < ApplicationController
def index
@posts = Post.find(:all, :limit => 10,
:joins => "LEFT JOIN `users` ON users.user_id = posts.user_id",
:select => "posts.*, users.username",
:order => "posts.created_at DESC")
end
end
如何從視圖訪問users.username?
我試過了
<% @posts.each do |post| %>
<%= post.username %>
<% end %>
但這似乎不起作用,因為我收到一條空白消息...
編輯:
我必須在LEFT JOIN中使用以下代碼:
:joins => "LEFT JOIN `users` ON posts.user_id = users.id",
嘗試這個 ..
@posts = Post.find(:all, :limit => 10,
:joins => "LEFT JOIN `users` ON users.user_id = posts.user_id",
:select => "posts.*, users.username as user_name",
:order => "posts.created_at DESC")
<% @posts.each do |post| %>
<%= post.user_name %>
<% end %>
我必須在LEFT JOIN中使用以下代碼:
:joins => "LEFT JOIN `users` ON posts.user_id = users.id",
您的代碼不是MVC友好的。 這是在Rails中更好的方法。
1.您的模型應執行以下查詢:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
scope :last_10, order("created_at desc").limit(10) #or "id desc" which is quicker
end
2.在控制器中調用查詢
class IndexController < ApplicationController
def index
@posts = User.find_by_username(the_username).posts.last_10
end
end
3.然后,您可以做
<% @posts.each do |p| %>
<%= post.user.username %>
<% end %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.