3

I have a lot pages in my app. And for every page I need to create a new variable and describe method. And if I will need to change something, I will have to change on every page. So the idea is to create universal method in application_controller.rb.

For example, I have a lot of categories in my Posts and to target some category for page I did: @posts_for_interesting = Post.where(interesting: true), other category, for example: @posts_for_photos = Post.where(photos: true).

And the application_controller.rb, have to look something like that:

def posts_for_all_pages(category)
  @posts = Posts.where(category: true)
end

And, for example, photos_controller.rb must look like that:

posts_for_all_pages(photos)

And how can I pass this photos to Post.where(category: true)?

1 Answer 1

3

Right here in your original code:

def posts_for_all_pages(category)
  @posts = Posts.where(category: true)
end

The category in Posts.where(category: true) will not a variable, it will be a hard coded symbol :category, so it won't work. Instead, write this:

def posts_for_all_pages(category)
  @posts = Posts.where(category => true)
end

a small change, but definitely has a different meaning.

Then when you call the method, you pass a symbol to it:

posts_for_all_pages(:photos)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.