I'm building a small admin page for my app that will display data from 4 models in one table. The columns are: Clubs, Users, Posts, Comments.
A club has_many users, a user has_many posts and has_many comments.
So my questions is do I need to add pagination explicitly to each of my 4 models in my admin_controller? The way it is now, I get the page list on the top and bottom of my table, and I can go back and forward pages, but all of my results are shown on the first page (~9000 results).
In my admin_controller I have
#clubs = Club.all.paginate(page: params[:page], per_page: 50)
and in my view
<%= will_paginate #clubs %>
<table>
<% i = 0 %>
<tr class="new-admin-top-row">
<td><%= "Club Location" %></td>
<td>| <%= "Number of Signups "%> </td>
<td>| <%= "Number of Posts By Users"%> </td>
<td>| <%="Number of Comments By Users"%> </td>
</tr>
<%= #clubs.find_each do |club| %>
<tr class="new-admin-row">
<td class="new-admin-cell"><%= club.name %></td>
<td class="new-admin-cell f"><%= #users_array[i] %></td>
<td class="new-admin-cell s"><%= #posts_array[i] %></td>
<td class="new-admin-cell"><%= #comments_array[i] %></td>
<td class="new-admin-cell"><%= #elevates_array[i] %></td>
<% i+=1 %>
</tr>
<% end %>
</table>
<%= will_paginate #clubs %>
The find_each method works on ActiveRecord::Relation objects and fetches 1000 records in batches. So that is where you problem most likely is. Change it to each and it'll probably solve your issue.
You can read more about find_each here: http://apidock.com/rails/ActiveRecord/Batches/find_each
Related
Rails newbie.. I'm getting an error on my join table index page.. but only sometimes. I'm confused since sometimes it works and sometimes it doesn't. Also when I go into pry and search for what is throwing the error, the item is there.
join table relationship:
post has many calendars/calendars has many posts
calendars_posts belongs_to calendars
calendar_posts belongs_to posts
calendar_posts controller:
def index
#calendars = current_user.calendars
end
index.html.erb:
<h1>Scheduled Posts</h1>
<% current_user.calendars.each do |calendar| %>
<h2> <%= calendar.name %> </h2>
<table>
<thead>
<tr>
<th>Title</th>
<th>Date</th>
<th>Time</th>
<th>Content</th>
<th>Link</th>
<th>Picture</th>
<th>Platforms</th>
<th>Finalized</th>
</tr>
</thead>
<tbody>
<% calendar.calendar_posts.each do |calendar_post| %>
<tr>
<td><%= calendar_post.post.title.titleize %> </td>
<td> <%= calendar_post.date%> </td>
<td><%= calendar_post.time %></td>
<td> <%= calendar_post.post.content %> </td>
<td> <%= calendar_post.post.link %> </td>
<td> <%= image_tag(calendar_post.post.picture_url, width: 200) if calendar_post.post.picture.present? %> </td>
<td>
<% calendar_post.post.platforms.each do |platform| %>
<%= platform.name.titleize %> <br>
<% end %>
</td>
<td> <%= human_boolean(calendar_post.post.finalized) %> </td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
I'm just confused because the error only happens sometimes... But once it starts happening then it happens every time I try to access the page after? Is there something I can do to ward off against nil?
I understand people are voting this down but I always do my research before posting and I finally figured out the issue. It was not like any of the other issues that showed up in related searches so it may be helpful for others to know... In my models I had Calendar and Posts with a join table CalendarPosts with user submittable attributes of time and date. The user can create a post and it floats separately from everything because I wanted someone to be able to jot ideas down as a "filler" and not be required to go further than that. This nil:nilclass error was coming from the fact that I had a dependency problem. My calendar_posts are dependent on posts. But I didn't have a dependency destroy in my post or calendar models. If a user deletes a post, the calendar post still existed but the post did not, which was the issue. Adding in the dependency destroy fixed my problem.
I realize the heading is a little confusing but my problem is quite simple. I hae two models in my rails 5 app. User and Expense. Each expense belongs_to a user. I have an index page where all expenses are being listed. I can list the user IDs for each expense from the expenses table but I want to instead look up the name of the user (in column username) in the users table and display it with the expense instead. The view I have written is below. But it doesn't work.
<p id="notice"><%= notice %></p>
<h1>Teamjournals</h1>
<table style="padding: 2px; width: 50%" border="2px" align="center">
<thead>
<tr>
<td align="center"><%= link_to new_expense_path, :class =>"btn btn-success btn-wide" do%>Add New Expense<% end %></td>
</tr>
<tr>
<th>User</th>
<th>Expense Date</th>
<th>Currency</th>
<th>Expense Amount</th>
<th>Description</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% #expenses.each do |expense| %>
<tr>
<td><%= User.joins(:expense).where('expense.user_id = ?', #user.id) %></td>
<td><%= expense.expense_date %></td>
<td><%= expense.currency.currency %></td>
<td align="right"><%= expense.expense %></td>
<td><%= expense.description %></td>
</tr>
<% end %>
</tbody>
</table>
Ok so in your iteration over #expenses you have this line:
<%= User.joins(:expense).where('expense.user_id = ?', #user.id) %>
you can change it to this:
<% user = expense.user %>
Note that I'm using <% not <%= because I'm just trying to assign a variable, not print the output to html.
Then after defining user you can say <%= user.name %>.
You should read a bit more about active record associations, but here's a few side comments about the query you've shown
User.joins(:expense).where('expense.user_id = ?', #user.id)
In this case, you should use the method generated by belongs_to instead of writing a query. But in situations where you do want to write a custom query, you should only be using where when you want to get an array. In this case you're looking for a single record so you could use find_by. Furthermore, the joins you're doing here is unnecessary
# any of these works
user = User.where('id = ?', expense.user_id).first
user = User.where(id: expense.user_id).first
user = user.find_by(id: expense.user_id)
I have been fighting this for a while.
I have a simple app that use users, timesheets and entries. timesheets belong to to users and an user has many time sheets. Entries belong to time sheets.
A user can click on a time sheet and be presented with the entries from that time sheet. I can create entries in the rails console and they show up correctly. But I am having trouble inserting the correct timesheet ID on the entries.
I may not be doing this correctly, but I have a link on the time sheet view to the entry view. I am having trouble bringing over the time sheet id to insert it in the the create entry view.
I am using a form_for that looks like this.
<%= form_for(:entry, :url => {:action => 'create'}) do |f| %>
<table summary="Subject form fields">
<tr>
<th>Customer</th>
<td><%= f.text_field(:customer_name) %></td>
</tr>
<tr>
<th>Order Number</th>
<td><%= f.text_field(:order_number) %></td>
</tr>
<tr>
<th>Time In</th>
<td><%= f.text_field(:time_in) %></td>
</tr>
<tr>
<th>Time Out</th>
<td><%= f.text_field(:time_out) %></td>
</tr>
<tr>
<th>Time Sheet ID</th>
<td><%= f.text_field(:time_sheet_id, :value => #sheet_id ) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Add Entry") %>
</div>
<% end %>
This is my entry controller.
def create
#time_id = TimeSheet.find(1)
#new_entry = Entry.new(entry_params)
if #new_entry.save
flash[:notice] = "New Entry has been Added!"
redirect_to(:action => 'index')
else
render('new')
end
end
Do instead:
#new_entry = time_id.build_entry(entry_params)
Sorry, I Am closing this.
It was poorly worded and I figured out the problem.
All I needed to do is run the form_for from my timesheets controller and redirect it to the entries controller.
This is probably a very simple question, I apologise - I'm new to rails.
I've got 2 controllers - customers and orders. I've got it so that when a customer places an order, their id is passed in a hidden field, so that the customer_id field in the orders table has their id. So all orders have the id of the customer who placed it. What I'm trying to do is have the show view for the customers display all their orders - so all the orders with their id.
I've got the customer has_many orders and orders belong_to customers etc. How do I reference the customers/orders to extract the right info? And do I need to put extra info in the show action on the controller? I've tried everything I can think of! So far, I've been able to get a hash of all the info to appear in the show view, but I can't get individual bits of info to appear - e.g. order.price.
I basically want a table of the order details in the customers show view - order price, date placed etc. Any help would be much appreciated, thanks!
Edit: I now have this - but can't get the line_items bit to work. The relationships work like this: customer has many orders, orders have many line items, line items belong to products. I suspect the reason it's not working is because of the belongs_to.
<% #customer.orders.each do |order| %>
<% order.line_items.each do |line_item| %>
<tr>
<td><%= line_item.created_at %></td>
<% line_item.products.each do |product| %>
<td> <%= product.name %></td>
<% end %>
<td><%= order.email %></td>
</tr>
<% end %>
<% end %>
You shouldn't need to add anything to the controller show action.
In your customer show view you presumably have access to a #customer object. Because of your has_many, that will have a collection #customer.orders. So, in the view, you can do something like
<table>
<thead>
<td>Item</td>
<td>Quantity</td>
<td>Price</td>
<td>Date Placed<td>
</thead>
<% #customer.orders.each do |order| %>
<tr>
<td><%= order.item.name %></td>
<td><%= order.quantity %></td>
<td><%= order.price %></td></tr>
<td><%= order.date_placed %></td>
</tr>
<% end %>
</table>
Obviously I'm making up the possible order fields you'd want to display, but this should give you the idea.
In your show action:
def show
#customer = Customer.find(params[:id])
end
In your routes.rb:
resources :customers
In your view:
<table>
<% #customer.orders.each do |order| %>
<tr>
<td><%= order.id %></td>
<td><%= And Other Your Order Fields %></td>
</tr>
<% end %>
</table>
I'm having a bit of trouble getting forms for a has_many association to work for a shopping basket. The view is displaying the basket and has a table row for each item. Each row contains a text field so that the user can set the quantity.
The problem is that only the first item row quantity is being passed through in params, even if the second item's quantity has changed too.
Can anyone help please?
Thanks,
Roger
The output of params in the debugger is below, only one line_item is being passed through.
(rdb:2624) e params
{"commit"=>"Recalculate",
"authenticity_token"=>"7TKnhmbBPFiKLzVqTipzH8PDyCrOnKiFixGQ37XDGNY=",
"_method"=>"put", "utf8"=>"✓", "action"=>"update", "id"=>"4",
"line_item"=>{"quantity"=>"3", "id"=>"6"}, "controller"=>"baskets"}
app/controllers/basket_controller.rb
class BasketsController < ApplicationController
def update
begin
#basket = Basket.find(params[:id])
# Can't do anything here yet since the correct parameters aren't being passed through.
rescue ActiveRecord::RecordNotFound
logger.error "..."
end
redirect_to basket_path
end
end
app/views/baskets/show.html.erb
<%= form_for #basket do |f| %>
<table id="items">
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
<% #basket.line_items.each do |item| %>
<%= form_for item do |g| %>
<tr class="<%= cycle('alternate', '') %>">
<td><%= item.product.name %></td>
<td>
<span class="decrement-quantity"><b>-</b></span>
<%= g.text_field :quantity %>
<span class="increment-quantity"><b>+</b></span>
</td>
<td class="price"><%= number_to_currency(item.total_price) %></td>
</tr>
<% end %>
<% end %>
<tr class="totals">
<td>Total</td>
<td><%= #basket.total_quantity %></td>
<td class="price"><%= number_to_currency(#basket.total_price) %></td>
<td></td>
</tr>
</tbody>
</table>
<%= f.submit 'Recalculate' %>
<% end %>
You're just creating a new form within the other form. Rails doesn't do anything magical just because you nest one form within another - which is what's causing the issue you're seeing.
The way to handle this situation is to use the fields_for helper and nested_attributes_for - see NestedAttributes for more information too.
I would checkout Railscasts: Complex Forms Part 1. After you watch that, you may be interested in watching Parts 2 & 3.
Ryan Bates covers using fields_for in an understandable and easy to learn fashion.