Unable to show data in rails view

Viewed 19

I am not able to show data in the view. I don't know why? When I do this in view

 <%= @p.inspect %>

It shows me this in view

#<ActiveRecord::Relation [#<Post id: 1, Title: "My First Post", Text: "The world with out worries", CommentsCounter: 1, LikesCounter: 1, created_at: "2022-09-17 21:41:08.544136000 +0000", updated_at: "2022-09-17 21:41:08.544136000 +0000", author_id: 1>]>

This is the controller function

def detail
    @p = Post.where(id: params[:id]).where(author_id: params[:idp])
  end

But when I try to show only the title like @p.Title it shows this error enter image description here

1 Answers

In ruby you can set queries to iterate through collections such as you code does. that means that it is always returning an array. Even if there is just one object inside this array, you need to select the object manually:

@p = Post.where(id: params[:id]).where(author_id: params[:idp]).first

notice that first?

However, an id is always unique, so your query does not make sense. Instead you should use

@p = Post.find(params[:id])

since you are already having the param for the id from the route itself. The where statement for the author does not work in this case. What you can do to access the author, assuming that your models are set up correctly is:

@p = Post.find(params[:id])
@p.author.name # "name" is just an example here.

If you need to return a collection use the code you wrote and iterate through it:

@p = Post.where(id: params[:id]).where(author_id: params[:idp])
<% @p.each do |posts| %>
<p><%= posts.title %></p>
<% end %>

but again, the where(id: params[:id]) does not make sense in this context, since where searches for all records of that model that have the given attributes, but there will always be just one.

Related