I have this part of code:
<% current_user.meta_accounts.each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
So, I want Rails to show all my MetaAccounts in list, but I get this:
<li>Wallet</li>
<li>Credit card</li>
<li>Debit card</li>
<li>Debts</li>
<li>javascript:void(0)</li> #This is the problem
So, it also shows me MetaAccount, which isn't created yet.
In my MetaAccounts table I have this. I'm using Postgres.
So, it also shows me the last row, where row_number is *. I don't know why, and how to avoid this.
Thanks for any help!
Try:
<% current_user.meta_accounts.select(&:persisted?).each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
The * row you see in PostgreSQL is not an actual record, it's just a quick way to create new records. If you want to be sure, run the following query:
SELECT COUNT(*) FROM MetaAccounts WHERE user_id=1
It will return 4.
I think the problem comes from an unsaved MetaAccount object in current_user.meta_accounts. This could be the case for instance in a form, where you build an empty object bound to the form. Make sure you don't have a call to current_user.meta_accounts.build(...).
If so, you can simply skip in your each loop all MetaAccount objects with a blank name.
Related
I am stuck on what seems should have a very simple solution, but I can not find anything that will work! I am iterating results from a table on the index page (which returns a list of states). This works without any problems when multiple records are returned. However, when a single record is returned, I get an error: undefined method 'each' for #
I know it is causing the error when only one record is returned, but I can not find any documentation on how to handle this, especially in the case that 1 or 0 records could be returned.
Code in controller:
#states = State.find(params[:id])
Code in index page:
<ul>
<% #states.each do |state| %>
<li>
<%= state.state_name %>
</li>
<% end %>
</ul>
Because you're using find, when you send multiple ids in the params, multiple records are matched; when you send a single id, a single instance is returned.
To ensure that each time, you get an ActiveRecord::Relation object that you can call each on, change your controller code to the following:
#states = State.where(id: params[:id]) # index action
You mentioned that it is the index view, so the above change should solve your problem.
If it's the show view, then you need to stick with find and change your view to display only one state.
You need to check if it responds to .each, which is the prime given for knowing if something implements the enumerable module.
if #states.respond_to?(:each)
# iteration goes here
else
# single handling goes here
Ofcourse you can also use the .where option in your query which returns always a collection
#states = State.where(id: params[:id])
Scenario 1:-
When record is queried in controller as:
#states = State.find(params[:id])
Then in view it should be like that:
<p><%= #states.state_name %></p>
Scenario 2:-
When record is queried in controller as:
#states = State.all
Then in view it should be like that:
<ul>
<% #states.each do |state| %>
<li>
<%= state.state_name %>
</li>
<% end %>
</ul>
Note:- In first scenario it is only one object but in second scenario it is a collection of object or a array of object. And only array are iterated.
I want to implement a search functionality in my Rails app by using the pg_search gem. I've set up everything like it says in the documentation. Then I've set up a search controller with a show action:
def show
#pg_search_documents = PgSearch.multisearch(search_params)
end
The search itself works but I have a really annoying problem in my view. Whatever I do, it always outputs an array of PgSearch::Document objects. Even when I only write this in my view:
<%= #pg_search_documents.each do |document| %>
<% end %>
I get this (I've shortened it):
[#<PgSearch::Document id: 2, content: "…", searchable_id: 28, searchable_type: "Vessel">, #<PgSearch::Document id: 3, content: "…", searchable_id: 27, searchable_type: "Vessel">]
I know that pg_search sets up a polymorphic association which I've never dealt with before — could that be the problem?
Thanks in advance
<%= #pg_search_documents.each do |document| %>
<% end %>
This is a classic error, one I remember being puzzled over when I first started learning Rails. The mistake is using <%= %> with each. The return value of each is the array that you're iterating over (in this case, #pg_search_documents), and by using <%=, you're telling Rails to create a string from that array and insert it into your view. That generally isn't what you want: you want the view to be generated by the code inside the block you're passing to each.
Use <% #pg_search_documents.each do |document| %> instead (omitting the =) and you'll avoid the dump of the array's content.
You may also need to use .searchable as #blelump suggests, but I wanted to answer the other half of your question, as it's a common pitfall.
To get back to the original source model, searchable call is needed on these search result records, e.g:
<% #pg_search_documents.each do |document| %>
<%= document.searchable %>
<% end %>
You can also switch back to the source model within your controller, e.g:
#pg_search_documents = PgSearch.multisearch(search_params).collect(&:searchable)
Then, the #pg_search_documents will contain Vessel elements.
I am trying to get distinct value from this controller. But I am not sure how to succeed.
Here the controller I have try this
#count = Present.where('event_id > ?', params[:id]).uniq.pluck(:customer_id)
But when I try to do this in my view
<% #count.each do | co | %>
<%= co.customer_id %>
<% end %>
I keep having this issues
Cannot visit Arel::Nodes::Distinct
I want to be able to preserve all Present Objects with the event_id equal to the id, but also being able to select only the one with distinct customer_id.
Update: after restarting the server i get the following error
undefined method `customer_id' for 1:Fixnum
Maybe you need to restart your rails server: https://github.com/rails/rails/issues/7399
Previous similar SO question
Update:
From the docs: When using pluck, "The values has same data type as column"
Change loop to:
<% #count.each %> do |i|
<%= i %>
<% end %>
In my rails app, i have the following function in one of my controller page.
def tree
#jstree = ActiveRecord::Base.connection.execute("Select sequence, depth, node, imageid, range from.....several joins")
end
I now want to loop through the resultset and display the sequence only in my view page tree.html.erb. I tried the following code, it does not seem to work.
<% #jstree.each do |tree| %>
<%= tree.sequence %>
<% end %>
I am getting the error message: undefined method 'sequence' for #<Array:0x60e0088>.
Is there a way of looping through the result set of the sql query executed and displaying each column value?
Many many thanks for all suggestion provided :)
Keeping the same syntax as the OP
<% #jstree.each do |tree| %>
<%= tree[0] %>
<% end %>
would accomplish what you were looking for.
You get this error because what you get in #jstree is a raw DB adapter result. If you want to query for some objects by issuing raw SQL queries then use find_by_sql. Example:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
I have created a very simple model called Discussion and one of the columns is a boolean called resolved. The idea being that once a discussion item has been resolved that value is set to true.
On the edit form, I tried to put in some logic based on the value of that field.
<%= form_for(#discussion) do |d| %>
...
<% if d.resolved == "true" %>
<p>The discussion is resolved</p>
<% else %>
<p>The discussion is not resolved</p>
<% end %>
<% end %>
However, I'm getting an error message
undefined method `resolved' for #<ActionView::Helpers::FormBuilder:0x00000101674678>
I tried adding an attr_accessor line to my model but that didn't do anything for me either. I'm not sure what I have to do to fix this. I'm pretty new to rails, so I'm sure that whatever the problem is it's probably pretty simple to fix, but I just don't get it. Thanks.
Because d represent an instance of the form builder, you want
<% if #discussion.resolved %>
If resolved is represented as a "boolean" in ActiveRecord.
every boolean column represents as predicate, so you can use:
if #discussion.resolved?
...
end
What you're looking for is the resolved? method.
<% if #discussion.resolved? %>
which is auto-generated for boolean columns.