Reputation: 81
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
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