user121212
user121212

Reputation: 149

How to pass different parameters from a controller?

I have 3 models as category, posts and comments. I want to display posts and number of comments in the category page.

category.(:id)Post.(:id).comments.count will return the number of comments.

But how should I pass those parameters from category controller? I'm also trying to write the jbuilder view for the same.

or Can I do something like this directly from jbuilder view?

#this work

json.number @category.posts.count

#this one doesn't work

json.number @category.posts.comments.count

Upvotes: 0

Views: 363

Answers (2)

Shiva
Shiva

Reputation: 12582

json.number @category.posts.count it works but json.number @category.posts.comments.count this does not.

You can test in rails console.. like @category.posts.comments.count. it may throw error like
NoMethodError: undefined method 'comments' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x0000000920b058>

This happens because @category.posts returns a collection not Post object.

One possible solution is
@category.posts.map {|post| [post, post.comments.count] } This gives you the total count of comments per post in array. This may not be exactly what you wanted but you may modify to meet your requirement.

Upvotes: 1

ABrowne
ABrowne

Reputation: 1604

The easiest way to pass parameters from the controller to a view you are going to present is using the @ (instance variable). Therefore you can pass:

@count = <your code above>
@all_posts = <your post code>

If you have alot of different parameters, just create an object to pass them across in:

@post_info = {
      count: <your code above>,
      all_posts: <your post code>
}

And then retrieve them in your view using @post_info[:count] and @post_info[:all_posts]

Upvotes: 1

Related Questions