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.
Related
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.
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.
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.
I am trying to create a search function in Rails 4. I have it implemented properly and it is displaying the result I want, however it is also returning and displaying the entire database query - All columns from table including password digest etc. I have done this before but haven't run into an issue like this. Would like to know if I am doing something wrong.
here is my controller:
def index
if params[:search]
#pro = Admin.search(params[:search])
else
#pro = Admin.all
end
end
Admin Model:
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
else
scoped
end
end
And here is my views:
<%= #pro.each do |ind| %>
<ul>
<li><%= ind.name %></li>
</ul>
<% end %>
in Chrome, I see the returned name of the individual from the search, as I would like, plus meta data such as id: 1, admin_id: 2, name "", email: "", password_digest: "" etc. in an array format. This is what's stumping me, not sure why it's displaying this.
When I inspect the page in chrome, the array is just pasted right under the tags.
It goes away when I remove the entire .each method on #pro. Any insight anyone can provide is appreciated.
The line in view should be <% #pro.each do |ind| %>. If you're doing <%= %> the result is the actual #pro array, which is why you're getting it pasted under the tags.
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.