在我们的网站上,我们有一个用户个人资料页面,我们希望显示与该用户个人资料相关的所有微博。
在我们的微博表中,我们有一个belongs_to_id列和一个user_id(定义微博的来源)
我们正在尝试将belongs_to_id与user_id匹配。这样,当查看配置文件时,仅显示belongs_to_id与正在查看的配置文件的user_id匹配的微博。我们怎么能这样做?
class Micropost < ActiveRecord::Base
attr_accessible :content, :belongs_to_id
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 240 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
# Return microposts from the users being followed by the given user.
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
# Return an SQL condition for users followed by the given user.
# We include the user's own id as well.
def self.followed_by(user)
following_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{following_ids}) OR user_id = :user_id",
{ :user_id => user })
end
end
UsersController:
class UsersController < ApplicationController
before_filter :authenticate, :only => [:index, :edit, :update, :destroy]
before_filter :correct_user, :only => [:edit, :update]
before_filter :admin_user, :only => :destroy
def index
@title = "All users"
@users = User.paginate(:page => params[:page])
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(:page => params[:page])
@title = @user.name
@micropost = current_user.microposts.build(params[:micropost])
end
答案 0 :(得分:1)
只有当你想要user_id AND belongs_to相同的帖子时,这是一个在MicroPost类中使用命名范围的方法:
micropost.rb
class MicroPost < ActiveRecord::Base
scope :relevant_to_user, lambda{|i|
where("user_id = ? AND belongs_to_id = ?", i, i)}
end
然后在控制器中:
def show
@user = User.find(params[:id])
@microposts = MicroPost.relevant_to_user(@user.id)
end
编辑:如果您只需要查找belongs_to_id与值匹配的微博(在本例中为current_user.id),请使用:
def show
@microposts = MicroPost.where(:belongs_to_id=>current_user.id)
end
答案 1 :(得分:1)
我不确定为什么Microposts belongs_to_id
和user_id
。但是如果你想找到belongs_to_id
匹配给定用户ID的所有Micropost,你只需要:
@microposts = Micropost.find_all_by_belongs_to_id(@user.id)