Prabhakaran8737
Prabhakaran8737

Reputation: 81

how to get the first category id in rails find method

I have the following in my controller

@posts = Post.where(category_id: params[:id]).paginate(page: params[:page], per_page: 20).to_a

I need to get the category id so i tried

@category = @posts.category_id.first

And i used it in view hidden field

<input type="hidden" value="<%= @category %>" />

How do i get the id in my hidden field and getting the error as

undefined method `category_id'

Upvotes: 0

Views: 86

Answers (1)

user229044
user229044

Reputation: 239551

@posts is an array. You cannot invoke a Post method on an array of posts. You need to pick one post from the array on which to invoke the method. To get the first one, you'd use @posts[0] or @posts.first. Now that you have a post, you can ask for its category_id:

@category = @posts.first.category_id

That said, you already have that same value at params[:id], so why not use that?

Upvotes: 2

Related Questions