2014-10-27 72 views
0

我是新来制定,我一直没能找到解决这个问题。我想/显示所有帖子未与用户相关联的当该用户已登录设计不是current_user方法?

我有以下模型关联:

user.rb

has_many :posts 

post.rb

belongs_to :user 

我该怎么做?我在寻找的线沿线的东西:

- not_current_user.posts.all.each do |post| 
    = post.foo 
    = post.bar 

是否有某种方法或途径可能做到这样呢?

如果我不清楚,或者如果我错过了这个问题的答案,请让我知道。

干杯

+0

难道你不是这个意思:'user.rb':'has_many:posts'和'post。rb':'belongs_to:user'? – Surya 2014-10-27 06:24:10

+0

@ User089247我愿意 - 谢谢!我相应地编辑了我的帖子。 – VoA 2014-10-27 22:09:20

回答

1

我猜你大概的意思:

user.rbhas_many :postspost.rbbelongs_to :user

你可以试试这个:

@posts = Post.where.not(user_id: current_user.id) 

然后在视图:

- @posts.each do |post| 
    = post.foo 
    = post.bar 
+0

谢谢 - 对不起,我的意思是(我编辑了我的文章以反映它)。 关于你的回复 - 这听起来像它会做到这一点!好主意,谢谢 – VoA 2014-10-27 08:17:05

1

使用posts = Post.where('user_id != ?', current_user.id)

然后posts.each do ...

1

首先,我建议在视图中不使用这种类型的逻辑。最好在其他地方使用这个逻辑,并在视图中渲染posts对象。这将您的视图逻辑从您的模型和控制器逻辑中分离出来。

要到不与用户相关联的帖子,现在你可以查询数据库

# app/controllers/posts_controller.rb 
@posts = Posts.where.not(user_id: current_user.id)  # syntax for Rails 4.0+ 
+0

是的 - 我一定会接受你的建议并从视图中剔除逻辑,谢谢! 作为一个说明 - 你知道你的建议是什么rails 4语法?干杯 – VoA 2014-10-27 08:21:48

+0

我的评论很混乱。这是Rails 4的语法('where.not')。 – ianks 2014-10-27 16:16:27

+0

啊!谢谢 - 总是很高兴知道更多的轨道魔术:) – VoA 2014-10-27 17:19:54

1
像这样的东西

大概:

post.rb

scope :all_other_than_created_by_user -> { |user| where(['user_id != ?', user.id]) } 

在控制器:

@posts = Post.all_other_than_created_by_user(current_user) 

,并鉴于喜欢使用它:

- @posts.each do |post| 
    = post.foo 
    = post.bar 

编辑:我改变了它实际做数据库查询在控制器,它比鉴于做得更好。

+0

使用'范围在模型'的方法或仅仅使用控制器来发布= Post.all_other_than_created_by_user(current_user)是更好吗?是否有性能差异? – VoA 2014-10-27 08:28:40

+0

最好使用范围方法。不要考虑性能,考虑分离MVC层。 – Esse 2014-10-27 10:34:32

+0

所以范围(过滤器)将在模型中进行,因为那是处理服务器数据的rails区域,它将是实现限制的最基本的地方。另外,保持控制器的薄型化通常会更好 - 是吗?感谢您的建议和帮助! – VoA 2014-10-27 17:21:49

相关问题