简体   繁体   中英

Devise not current_user method?

I'm new to devise and I haven't been able to find a solution to this problem: I want to get/show all posts not associated with a user when that user is signed in.

I have the following model associations:

user.rb

has_many :posts

and post.rb

belongs_to :user

How might I do this? I'm looking for something along the lines of:

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

Is there some method or approach which might accomplish something like this?

If I'm not being clear or if I happened to miss an answer for this please let me know.

Cheers

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

Then posts.each do ...

Firstly, I would recommend not using this type of logic in the view. It is best to have this logic elsewhere, and just render the posts object in the view. This decouples your view logic from your model and controller logic.

To get to posts NOT associated with the user, now you can just query the database

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

Probably with something like this:

post.rb

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

In controller:

@posts = Post.all_other_than_created_by_user(current_user)

And use it in view like:

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

Edit: I changed it to actually do database query in controller, it's better than doing it in view.

I am guessing you probably mean:

user.rb : has_many :posts and post.rb : belongs_to :user

You can try this:

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

then in view:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM