Jacob Montgomery


34,480 Experience
33 Lessons Completed
41 Questions Solved


Posted in How do I display several posts in related "weeks"

Ah, yeah this is basic MVC

In your controller you'll have something like:

class VisitorsController < ApplicationController
  def index
    @latest_posts = Post.last(4)

then in your app/views/visitors/index.html.erb you'll iterate over @latest_posts and output the relevant data there... something like:

<% @latest_posts.each do |post| %>
  <h1><%= post.title %></h1>
  <p><%= post.description %></p>
  <%= image_tag post.image_url %>
<% end %>

Posted in How do I display several posts in related "weeks"

For the boxes on the home page, if you just need the last 4-6 posts just do something like Post.last(4), no need to use the gem for that one.

Chris has some great videos on managing files / images. Check out https://gorails.com/series/direct-uploads-to-amazon-s3 - after going through those you should have no problem dispaying whatever photos you want along with your posts.

Glad I could help! Have fun!

Posted in How do I display several posts in related "weeks"

Hi Sebastian,

Depending on how much control you really need, the simplest would probably be to just add an integer week column to your Post model for you to enter the week number when creating the post. This would allow you to do something like Post.where(week: 3) to get all the posts that are in week 3. You could potentially automate this if you set a fixed start time, then you could just calculate how many weeks have passed since the start time to fill in the week #.

You could define a Week model where a post belongs to a week. This would be setup similar to a Category model in relation to a blog but I don't think it's a very efficient way to handle this particular scenario, but I could be totally wrong.

You could also look into the groupdate gem which would allow you to group records together based on a given time range at the time of your query. This is probably the "right" way to do it, but I believe you'd still need to define a fixed start date so you can properly count how many weeks have passed to properly label each grouping "week 1, week 2, etc..."

That's about all I can think of, there may be more clever ways to handle...

Posted in Sortable Drag and Drop

Displaying ok != working ok

Result of params shows that the ID's aren't being grabbed by the JS. So since all your code on the JS looks good, then the process of elimination is saying it's because you're defining your id on the <td> instead of <tr>

Did you move id: dom_id(product) to the <tr> tag?

Please do that and then test. I just modified one of my implementations and it does not work if I put the ID on the <td> tag but it works as expected when I move it to the <tr> tag.

Posted in Sortable Drag and Drop

Sorry, small correction to the byebug instructions...

You'll refresh your page and then try rearranging your rows. The first time you move a row into a new slot it should fire the ajax request which should now trigger the byebug instance in your console. Now you can type in params and see the params that were sent over in the request to see if you're getting anything at all related to your rearranged rows.

Posted in Sortable Drag and Drop

Ahh, I think your problem is how you're identifying your sortable objects. I haven't tested this or even done the sorting on a table so this could be wrong, but you're putting the id: dom_id(product) on a <td> tag and I believe it should be on the <tr> tag.

As for the byebug result, you should do something like this:

def sort
    params[:product].each_with_index do |id, index|
        Product.where(id: id).update_all(position: index + 1)

    head :ok

And then refresh the page. Now look at your terminal where you started your rails server at and you should now have a command prompt where you can type in params then hit enter and get the params for that request. https://github.com/deivid-rodriguez/byebug

Posted in Sortable Drag and Drop

Hi Clay,

If you throw a byebug in your action before you start iterating, you'll get a console where you can test what the params are and see if the id's are even present in the params hash or that your key is actually :product.

Can you post your view where you have your sortable list and the js?

Hi Rajnish,

options_for_select expects an array or hash of options, see https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select

Your query - @select = Store.find(current_user.store_id) only returns a single object which won't work to populate a select field like you're wanting.

So just to clarify what you're after, can a User have multiple stores or only one? Your query suggests only one, but your desired result suggests multiple so I'm a little confused.

Jacks answer is spot on if a user can have multiple stores. If so, you should adjust your query to something like @select = current_user.stores if you have your associations setup correct.

Posted in Need some help with an Active Record Query

Assuming you're using devise, to get all the stores that the current_user has access to, the query would be

@stores = current_user.stores

Posted in Need some help with an Active Record Query

Hey Simon, 

You should be able to use a through association here to get what you want.

has_many :farms
has_many :stores, through: :farms

Check https://stackoverflow.com/a/11601221/3670272
Hey Francisco, 

As Jack stated, you just need a cron job to check for records that expire in 30 days or less. So on your Post model you would store an expiration date or just check the created_at timestamp and then in your cron you could check for all records that have an expiration date that is less than 30 days from now with a scope. Eg:

scope :expires_in_30_days, -> {where("expiration_date < ?", Time.now + 30.days)}

Post.expires_in_30_days.find_each do |post|

Hi Youssef,

You can use route constraints to manage this.

Check out this gist: https://gist.github.com/nanosplit/b49fadaff9c4342ac4bd72cbd325495a

Good read: https://mythoughts.io/managing-dynamic-domains-with-rails-b6ab1040dc8c
Ahh, yeah in this case I think it's the best you can do (I'd love to be proven wrong though!!). 

One thing I forgot to include was you need to have a "next" in the rescue so your loop continues after the exception is rescued... 

 rescue => e
    failed_count += 1
    failed_records << cat
    ActivityLog.create(:act_type => "Insert", :act_action => "", :updated_by => "System", :activity => e, :act_tstamp => Time.now)
    next #continue the loop

Unfortunately anytime you need to have validations it's going to slow down your importing. 

You could potentially do some reengineering where you first load an array of category names and then compare your categories array and reject any that match. This would be more performant than checking the validations on save, which you could then use the ActiveRecord Import gem to really speed up your saving, and you could still construct an array of objects that get rejected along with the count of success/failures. However, depending on how exactly all these categories are hitting your app you could be caught up in race condition issues... but if its a controlled process for retrieving these categories and saving them then you shouldn't have any issues.
Aye, too long!!

What I gave should work fine in Sidekiq, I don't believe anything there is unique to Rails in any sense that would fail upon execution but I could be wrong.

How many categories would you be processing at once under normal use? I don't think there's any issue with building the array of items to insert, what alternative would you use?

Hey Alan, 

One method would be to iterate through the categories within a begin/rescue block and catch the exceptions... so something like: 

failed_count = 0
failed_records = []

categories.each do |cat|
  rescue => e
    failed_count += 1
    failed_records << cat
    ActivityLog.create(:act_type => "Insert", :act_action => "", :updated_by => "System", :activity => e, :act_tstamp => Time.now)

completed_status = "Created #{failed_count}/#{categories.count} categories, #{failed_count} failed."

# do something with the failed_records array

If you're doing large batches then this isn't going to be very performant, but I'm not sure how you'd rescue and get the error message for individual failures when working with batches like your initial example gave.

Posted in Can anyone see the error here?

uninitialized constant RecipesController::Category

Sorry, I didn't see that line before

As Toan said, check the spelling and file names for your category model. You should have a file in the models directory called category.rb (all lowercase) with class Category < ApplicationRecord (rails 5+) or class Category < ActiveRecord::Base if <= Rails 4

Posted in Can anyone see the error here?

Hey Alan,

What exactly is the error message?

Also, you should be able to accomplish the same thing using pluck which is more performant, you also don't have to use `all` for this:

@categories = Category.pluck(:name, :id)

Hey Joel, 

Is the name of the category in the url of the previous page? 

If so, then 


will give you the url of the page that sent you there.

Otherwise, you can just pass it as a param that would appear at the end of your url ?cat=meow
Woohoo, glad that worked for you!

Good luck!

Posted in DB Structure for custom forms

Hey Luca, 

Thanks for the link! I had that same article bookmarked from a while back but never made it back to it, haha!

I think I have a better idea of what you're talking about here now, so I still think the need for multiple forms to be attached to a single record could be accomplished by just adding another layer to the json you store as I previously mentioned... you'll just have to do a little more work to make sure it's the proper version being fetched.

As for your other issue: I would like to move from this method as it has some limitations, one being that by modifying the form template (i.e. adding/removing fields) every existing record should be also modified.

I really have a bad feeling about handling it this way. If you add a new field to a form, then every old form would be updated to just have a nil value since it would require the user to come back to the form and update it. If you remove a field, then once every other record is updated, that data is gone for good (unless you do a soft delete, but that's a whole new issue), so a simple mistake (accidentally deleted the wrong field) could have a horrific ripple effect. So I think if you instead just did versions of a form, you could add or remove fields without being so destructive.

However, there could be some legit reasons to have this ability, but I'm really not sure of a good way to handle this "automagically" without doing what I mentioned in my first response by making a method that checks if a field has been added or removed upon save, and then go through each saved record and adjust the saved json string accordingly. I just don't know of any other way for the database to know a value in a json string has changed and therefore must update every other instance of that particular form that has been submitted previously. If you figure this out, please come back and share!

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

© 2023 GoRails, LLC. All rights reserved.