1

我有一个用户帖子表,其中一些是私有的,由表中的布尔列(隐私)表示(真正是私有的)。在我的实时提要视图 (posts/index.html.erb) 中,我只想显示所有用户的非私人帖子。我可以通过我的范围做到这一点吗?

注意:在我的用户源视图中,我正在显示 current_user 的私人和非私人帖子。

Post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  # the top scope is sorting by "featured" posts (a boolean column in the Posts table)
  scope :livefeed_order, order('featured DESC, created_at DESC').limit(40)
  scope :userfeed_order, order('created_at DESC')
end

post_controller.rb

class PostsController < ApplicationController
  before_filter :signed_in_user, except: [:show]

  def index #Livefeed
    @posts = Post.livefeed_order
  end
end

users_controller.rb

class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:edit, :update, :show]

  def show
    @user = User.find(params[:id])
    @posts = @user.posts.userfeed_order
  end
end

帖子/index.html.erb

<%= render @posts %>

用户/show.html.erb

<%= render @posts %>
4

2 回答 2

3

Rails >=4.1 不再允许名称与 BLACKLISTED_CLASS_METHODS 匹配的范围(IE public, private, protected, allocate, new, name, parent, superclass... 请参阅GitHub 上的BLACKLISTED_CLASS_METHODSdangerous_class_method? )。所以, ...

...而这:

scope :public, -> { where(privacy: false) }

...适用于 Rails <4.1,您可能想尝试类似的东西

scope :only_public, -> { where(privacy: false) }
scope :only_private, -> { where(privacy: true) }

...以确保未来的兼容性。

于 2015-07-31T00:53:46.283 回答
1

您可以创建另一个名为 say 'public' 的范围,

#in your model
scope :public, lambda { 
  :conditions => { privacy: false }
}

#in your index action
@posts = Post.livefeed_order.public

想法是,您可以链接范围,

高温高压

于 2013-11-07T22:55:05.083 回答