Unable to show data in rails view - ruby-on-rails

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

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

Rails - Index action showing database record under post

I'm not exactly sure what I'm doing wrong here, but my index action is returning a bunch of information directly from the database underneath each record:
First Post!!!
Hello. This is my first blog post
[#<Post id: 1, user_id: nil, title: "First Post!!!",
content: "Hello. This is my first blog post", created_at: "2016-02-26 20:51:57",
updated_at: "2016-02-26 20:51:57">]
index.html
= for p in #posts
%h1
= p.title
%p
= p.content
You problem is that you are evaluating and outputting your for, in haml when you use = it is the same to use <%= %> in erb, it means that your code will be outputted once it is evaluated, that's why you are seeing that information from the database.
For solve your issue just use the "evaluator" tag in haml that is - it is the equivalent of <% %> in erb, that means your code will be ONLY evaluated and will not print any information to the screen.
Also as a suggestion do not use for when looping your objects in rails, use iterators like: #posts.each do |p| instead of for loop.

ruby on rails: Why does the model data appear in the browser?

I'd like to create a simple blog without the scaffold generator. I generated the controller and manually created the views.
First I define the create action( including def new) in the controller and then I proceeded to make the views. After that, I create a model called article and added fields like title and body. The show views are alright but when I created the index page and looped through all the articles, the model data are also shown.
First article <3 Second Article
[#Article id: 1, title: "First article <3", body: "This is the body of
the first article and i create...", by: "Ahmad Aziz", created_at:
"2015-03-30 11:50:03", updated_at: "2015-03-30 11:56:37">, #Article
id: 2, title: "Second Article", body: "This is the second article",
by: "Ahmad Aziz", created_at: "2015-03-30 11:53:31", updated_at:
"2015-03-30 11:57:13">]
How can i remove the model data from the index page? thank you.. I am sorry if my explanation is bad. I don't really know what this thing is called.
I'm using rails 4.2.
You would need to loop through your model and call the fields that you want on to display on the page...ie:
index.html
<% #articles.each do |article| %>
<h1> <%= article.title %> </h1>
<p> <%= article.body %> </p>
<% end %>
If you just print the article itself, you're going to get the who object
Make sure you aren't doing something like
<%= #articles.... %>
Somewhere.
That "=" right there would print the object.

Sorting objects Rails

I'm trying to sort some items that I am receiving from my database. Currently, I have a series of objects that get returned from my Tool model. Right now, I am retrieving some tools from my database, by using the following code (in my toolkit_controller):
def index
#tools = Tool.order('name ASC').all
end
This seems to be working fine and as intended. When I do this, I get the following result set (omitted some of the extra results for clarity).
[#<Tool id: 1, name: "Hammer", description: "A basic hammer",
created_at: "2013-07-07 16:46:13",
updated_at: "2013-07-07 16:46:15">,
#<Tool id: 2, name: "Mallet", description: "A fancy
mallet", created_at: "2013-07-07 16:46:13", updated_at: "2013-07-07 16:46:15">,
#<Tool id: 3, name: "Screwdriver", description: "A screwdriver",
created_at: "2013-07-07 16:46:13", updated_at:
"2013-07-07 16:46:15">,
#<Tool id: 4, name: "Torch", description: "A cheap torch", created_at:
"2013-07-07 16:46:13", updated_at: "2013-07-07 16:46:15">, ....]
What I'm struggling with right now is how to display my tools in a vertical fashion (rather than horizontal) on my erb page. To help paint a clear picture of the sort order I want, please take a look at this post: Ruby on Rails change array display order.
My display code is as follows:
<%= #count = 0 %>
<div>
<% #tools.each do |t| %>
<% #count = #count+1 %>
<div class="individualTool">
<%= t.name %> <%= #count %>
</div>
<% if #count == 4 %>
<% #count = 0 %>
</div>
<div class="row-fluid">
<% end %>
<% end %>
As you can see, the above code works fine to display the tools by name from left-to-right (e.g. Hammer, Mallet, Screwdriver, Torch), but my goal here is to display them from top-to-bottom, in an order as seen here: Ruby on Rails change array display order.
In the post that I linked, someone suggested using .each_slice(3).to_a.transpose.flatten (to try and correct the sort order), but when I tried that on the #tools that were being returned, I received an error message stating that the element size differs.
Any ideas on how I can accomplish this would be great!
Thanks in advance.
All, thank you for the input. I guess I'm still a bit confused as to why this wouldn't be considered a ruby sorting problem of which we could solve. After doing a bit more research on my own, I figured out how to solve the problem. The solution works as follows:
In my index method of the toolkit_controller, I have the following:
def index
#tools = Tool.order('name ASC').all
aAllTools = []
for i in #tools
aHashedTool = {}
aHashedTool["name"] = i.name
aHashedTool["description"] = i.description
aAllTools << aHashedTool
end
#outcome = aAllTools.each_slice(4).to_a.transpose.flatten # Corrects the order.
logger.debug "#{#outcome}" # Verified. Order is now correct.
end
By using the code above I was able to simply loop over the values like I had been doing in my question and everything seems to work. If there is a more optimal solution (or perhaps I should post a CSS question as well), then I would be happy to entertain it. Thanks again and I do appreciate your replies.

Rendering link_to from application helpers

Im trying to render a dynamic nav menu using a application helpers but all get is a hash
when I load the page this is all that it displays
[#<Project id: 15, title: "downer", created_at: "2012-07-03 08:36:16", updated_at: "2012-07-03 08:36:16", company_id: 2>]
here is the code that is used in the application helper
def project_list(user)
company ||= user.profile.company
projects ||= company.projects
projects.each do |project|
link_to project.title, company_project_path(company, project)
project.scopes.each do |scope|
link_to scope.name, company_project_scope_path(scope.company, scope.project, scope)
end
end
end
and
_nav.erb.html
<%= project_list(current_user) %>
In ruby a method returns the last evaluated expression by default. Also, each returns the array/hash which was iterated upon. So effectively your project_list is returning projects back to the view. You should change your method to return the html you want to insert:
def project_list(user)
html = ''
company ||= user.profile.company
projects ||= company.projects
projects.each do |project|
html += link_to project.title, company_project_path(company, project)
project.scopes.each do |scope|
html+= link_to(scope.name, company_project_scope_path(scope.company, scope.project, scope))
end
end
return html.html_safe
end
Your enumerable #each is returning the last object in the collection which becomes the return value of the project list method.
You need to build up a list of tags then return that object.
If you are using 1.9.2 you could use each_with_object either with a string as on object or an array that you could join before returning it.

Getting "undefined method `content' for #<ActiveRecord::Relation:> " error when trying to get content from table row

When I put #user.dreams in my view, I get:
[# Dream id: 3, content: "My Dream", user_id: 2, created_at: "2011-10-06 21:58:50", updated_at: "2011-10-06 21:58:50">]
Now I want to print out JUST the content: data from this row. But when I put:
#user.dreams.content or #user.content
I get the "undefined method `content' error.
#user.id correctly prints out "2".
How do I print out the "My Dream" content from this row?
if dreams is an association on user then you would need to do
#user.dreams.first.content
or iterate through #user.dreams
eg
<% #user.dreams.each do |dream| %>
<%= dream.content %>
<% end %>
The dreams call is returning an ActiveRecord::Relation object because it's a collection of objects. If you want all the content for all the dreams you will have to treat it like an array:
#user.dreams.map(&:content)
Also, #user.content won't work because content is an attribute on a Dream object, not a User object.

Resources