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

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.

Related

Unable to show data in rails view

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.

Trouble with "show" and "index" routes in model with many to one relationship Ruby on Rails

I feel like the solution to this is actually quite simple but I can't figure it out.
https://github.com/kingdavidek/StuddyBuddy
I am writing an app to help me summarize non fiction books. I want to have a view for the book(or Piece) and then a one to many relationship with chapters/sections, where each section has its own view. I also want the ability to make subsections with many to one relationship to sections etc.
So this will be a kind of tree like structure where each smaller section will have its own summary. (I am basically following the jumpstart lab blogger project but adapting it for my own use. http://tutorials.jumpstartlab.com/projects/blogger.html#blogger-2 )
I have been able to create the view for the piece successfully and links to the sections. I got to the part with the comments on the jumpstart tutorial, where Comments have a many to one relationship with Articles, and where comments are displayed under the parent article. I wanted to use the same concept for sections/chapters, except that I would like to link to each individual section and display by itself in a new view.
the routes for the section model say:
piece_section GET /pieces/:piece_id/sections/:id(.:format) sections#show
piece_sections GET /pieces/:piece_id/sections(.:format) sections#index
I am having trouble displaying an individual section in a new page.
My first problem is that I cannot link directly to the show action of an individual section, and I don't know why:
Here is the relevant part in show.html.erb for the parent "Piece" or book:
<% #pieces.sections.each do |section| %>
<li>
<%= link_to section.name, piece_section_path(section), class: 'section_name' %>
<!-- this middle part 'piece.name' is the psart we want the link to say, the next part is our route helper.-->
</li>
<% end %>
<%= link_to "delete", piece_path(#pieces), method: :delete, data: {confirm: "Really delete the article?"}
%>
the parent "Piece" controller:
def show
#pieces = Piece.find(params[:id])
end
When i try to do this I get the following error:
ActionController::UrlGenerationError in Pieces#show
Showing /home/david/Documents/Learning/StuddyBuddy/app/views/pieces/show.html.erb where line #9 raised:
No route matches {:action=>"show", :controller=>"sections", :id=>nil, :piece_id=>#<Section id: 1, name: "xama", broader_context: "hahahah", summary: nil, key_questions_addressed: nil, thoughts: nil, piece_id: 1, created_at: "2016-07-28 10:46:05", updated_at: "2016-07-28 10:46:05">} missing required keys: [:id]
<%= link_to section.name, piece_section_path(section), class: 'section_name' %>
When I link to the index action of the sections model it works however, and I see the "show" action of the parent "Piece" perfectly fine.
My SECOND problem is when I am on the view for the Piece. I try to click on an individual section (ie. this link:
<%= link_to section.name, piece_sections_path(section), class: 'section_name' %>
)
And for some reason I cannot display the section and the columns of the Section model.
Here is the section controller:
class SectionsController < ApplicationController
def index
#pieces = Piece.find(params[:piece_id])
#sections = #pieces.sections.find(params[:section_id])
end
def show
#sections = Section.all
##sections = Piece.sections.find(params[:id])
##sections = #piece.sections.all
##sections.piece_id = #pieces.id
end
end
Here is the index.html.erb file for the Section model:
<h1> Yoyo</h1>
<p>Piece: <%= #pieces.name%></p>
<p> Section: <%= #sections.name%></p>
<p> Broader Context: <%= #sections.broader_context %></p>
Here is the routes.rb file:
Rails.application.routes.draw do
root to: 'articles#index'
resources :pieces do
resources :sections
end
end
The problem i get is this:
ActiveRecord::RecordNotFound in SectionsController#index
Couldn't find Section without an ID
Request
Parameters:
{"piece_id"=>"1"}
What I don't understand here is how I do not have access to the section id?? How is it I only have access to the piece_id??
I would really appreciate the help as I have been stuck on this for a while.
Pass piece id to link to helper as piece_section_path need two params
piece_section GET /pieces/:piece_id/sections/:id(.:format) sections#show
:piece_id
:id (section_id)
Change your link to:
<%= link_to section.name, piece_section_path(#pieces, section), class: 'section_name' %>

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.

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.

Ruby on Rails. Views showing full objects

my views are showing full objects like so:
dbwest hi [#<Tweet id: 1, tweet: "hi", created_at: "2013-05-25 12:16:40", updated_at: "2013-05-25 12:16:40", user_id: 1>]
I just want
dbwest hi
Has anybody else every seen something like this?
more code I'm pasting on request:
<%= #users.each do |user| %>
changing it to
<% #users.each do |user| %>
you may have something like <%= #tweet = Tweet.first %> which would display the whole object in your view, when you mean to just "find the first tweet" <% #tweet = Tweet.first %> With no code it's hard, but that is in essence what is happening. If anyone reading on the web, don't find in a view this way. Again, not saying this guy is but bad form. stuff that spit in the controller and reference the ivar #tweet later in your view.

Resources