I'm trying to list all records from the database in the main page.
Model and controllers were both created properly (I suspect) since using the following code and pointing to proper address (http://localhost:3000/subdomainw1s) lists all the records:
in /app/views/subdomainw1s/index.html.erb:
<h1>subdomain word 1</h1>
<ol class="subdomainw1">
<% #subdomainw1s.each do |sdw1| %>
<li>
<%= sdw1.blognamew1 %>
</li>
<% end %>
</ol>
However, attempting to past the same code in /app/views/home/index.html.erb results in an error message ("undefined method `each' for nil:NilClass") complaining about:
<% #subdomainw1s.each do |sdw1| %>
Clearly, rails doesn't know what to do with this model under the home page.. no?
Any advice would be great.
there is at least two more "codeless" options
convert it to (empty) array
..#subdomainw1s.to_a.each do |sdw1|..
or use method try
..#subdomainw1s.try(:each) do |sdw1|..
copy the code to collect the subdomains from 'index' in subdomains controller to 'index' in home controller.
Related
I'm pretty new to ruby/rails so bear with me.
I'm attempting to take the results returned by the JIRA rest API and render them in a view. I can do that pretty easily using the jira-ruby gem. The problem I'm having is grouping the results by a specific object inside the object returned by the API (in this case, a "components" field object inside of a "issue" object). I've attempted to use group_by and chunk for this but I'm basically getting the inverse of what I want. Both methods return the same result.
In my controller I have:
#issues = #jira_client.Issue.all
In my view I have:
<% #issues.chunk {|issue_comp| issue_comp.fields["components"]}.each do |comps, issues| %>
<h2>
<% comps.each do |comp| %>
<%= comp["name"] %>
<% end %>
</h2>
<ul>
<% issues.each do |issue| %>
<li><p><%= link_to issue.key, "http://localhost:2990/jira/browse/#{issue.key}" %> - <%= issue.summary %></p></li>
<% end %>
</ul>
<% end %>
What I end up with is:
CompA CompB
IssueA
CompC CompD
IssueB
CompA CompC CompD
IssueC
etc.
What I want is:
CompA
IssueA
IssueC
CompB
IssueA
CompC
IssueB
IssueC
CompD
IssueB
IssueC
The object returned by the API is a pretty convoluted object (i.e. giant array of hashes inside arrays inside of hashes). So, I have to dig pretty deep to get at the component name.
I get the feeling that this shouldn't be as complicated as it seems but I have a terrible habit of making things more complicated than they need to be. What am I doing wrong here?
EDIT: I created a gist of the full dump that is returned with the above call. Notice the "components" array:
jira-ruby gem dump for all issues
I took a look at the data you're getting back from Jira. This is how it looks to me:
There is an outer array of Jira Issues.
Each issue has an "attrs" hash
Each "attrs" hash contains components.
If this understanding is correct, I think you are attempting to invert that structure so that you can get a complete list of components, then iterate over each of them, and show the Issues that belong to that component.
If that understanding is correct, you have two basic choices:
Check if you can ask Jira for that information (so you don't have to generate it yourself), or
Build your own data structure (in memory on in a local DB as you prefer):
Some sample code for building a useful structure in-memory:
# in a controller, model, or service class (as you wish)
#components = {}
#jira_issues_array.each do |jira_issue| # from your API call
jira_issues[:components].each do |jira_component|
#components[jira_component[:key]] ||= { name: jira_component[:name], issue_keys: [] }
#components[jira_component[:key]][:issue_keys] << jira_issue[:key]
end
end
In your view, you could iterate over #components like this:
# some html.erb file:
<h1>Components and Issues</h1>
<ul>
<% #components.keys.each do |component_key, component| %>
<li><%= component[:name] %>
<ul> <!-- nested -->
<% component[:issue_keys].each do |issue_key| %>
<%= #jira_issues_array.find { |issue| issue[:key] == issue_key }[:name] %>
<% end %>
</ul>
</li>
<% end %>
</ul>
Note: Like a typical lazy programmer, I haven't tried this out, but it's really intended to show how you might go about it. For example, each issue's name is embedded in the attrs section, so you'll need to dig that out a bit.
Finally, if anyone would find this useful, I use this to analyse and reformat JSON.
HTH - any questions or problems, post a comment.
I've tested a couple of methods for printing the first 3 instances of my class for a Ruby on Rails application. I've already got the following working :
<%#posts.each do |post| %>
<div class ="post content" >
<h2 class="title"><%=post.title%></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y")%></p>
<p class="body"><%=post.body%></p>
</div>
<% end %>
But I'm trying to do the same thing but only printing the first 3 elements of the #posts variable.
.first(3) and .find(:id) haven't worked and I'm at a loss on how to iterate through the class variables.
Thanks.
If you only need 3 posts and don't require the rest anywhere in your view, then filter them out in your controller and don't query for unused models.
In your controller:
#posts = Post.limit(3) # Post.where(x: 'y').limit(3)
You want to use take.
<% #posts.take(3).each do |post| %>
first works in a similar manner (but it orders by id), and should get the job done as well.
PS: You should consider moving this logic in the controller.
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 have a piece of code which displays a complicated 'listing' of resources. by complicated i mean that it has name, date, time posted, number of comments, picture, description, and tons more things that you obviously only want to write that block of code one time.
I'm trying to think of how this would go into the rails architecture and I'm at a loss
i need to display the resource listing using a different variable in different controllers. currently its in a partial called _resource_view.html.erb
This is fine for the main listing, but its not usable for the persons profile listing, which takes the same format but shows different resources
_resources_expanded.html.erb
<ul class="res-list">
<% #resources.each do |resource| %>
... list stuff
<% end %>
</ul>
It uses #resources on index, but on the profile page it uses the same listing code except its #user.resources.each do |resource|
I was thinking maybe something like this but this seems redundant .. and im not even sure if it will work
<ul class="res-list">
<% #resources.each do |resource| %>
<%= render 'layouts/resources_expanded' %>
<% end %>
</ul>
Don't use instance variables, use local variables in the partial - that lets you pass in a single each time through the #resources.each loop.
<%= render 'layouts/resources_expanded', :resource => resource %>
and then in _resource_view.html.erb change #resource to resource
I recently decided I wanted to list all the users in my Ruby On Rails application - since I couldn't figure out how to list them any other way, I decided to use partials.
I have the following on my administration page (just hooked up to a its own administration controller):
<%= render :partial => User.find(:all) %>
I then have a file called _user.html.erb in my users view folder. This contains the following:
<ul>
<% div_for #user.object_id do %>
<li><%= link_to user.username, user.username %></li>
<% end %>
</ul>
When the application runs and I go to the administration page, I get the following error:
undefined method `id' for 4:Fixnum
It says it's because of this line (which is in the partial file):
<% div_for #user.object_id do %>
I'm unsure why this happens (and have googled for hours to try and find results and only find solutions that don't work for me). I think it's something to do with my usage of the #user instance variable, but I'm not totally sure.
You get that error because div_for expects an active record object as an argument, which it calls the id method on. You pass in a fixnum (the result of #user.object_id), which is not an active record object and does not have an id method.
So pass in #user instead of #user.object_id and it will work.
Also you should use user instead of #user, rails 3 does not set instance variables for partials anymore.
Lose the .object_id part. I seriously can't think why are you using object_id!Do you have a good reason for doing so? Anyway div_for wraps a div around an object, so leave the .object_id part!
instead of object you are using it's column or visa varsa you are using at that time you will get this kind of error.
Example
I am using id instead of user = User.first object.
Try this, it worked for me.
#item.unit_of_measure.name
instead of
#item.unit_of_measure_id.name