Jacob Montgomery

Joined

34,500 Experience
33 Lessons Completed
41 Questions Solved

Activity

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

Can you link to the SO question so I could see what he's referencing, and do you by chance have the ability to share the repo?

From the sounds of it, you're wanting the ability to attach multiple photos to a single post. If so you can ignore my last message as that was if you only had a single file attached to the Post model.

  • Also for consistencies sake in your code either call it image or photo.

Is this what you're unsure of? If so, all he's saying is to have continuity in your naming conventions. Imagine you're reading a book, and for no reason the main character's name changes. Then a few sentences later, they're back to calling the character by their original name. Doesn't make much sense to do that does it?

  • How do i migrate it like that without killing everything?

Since I can't see what you named everything, I don't want to make assumptions and cause any further confusion. If you can provide the SO link and/or repo I can take a look and see if I can help explain.

For migrations, check out: https://www.driftingruby.com/episodes/activerecord-migrations (should be a free episode). All a migation is doing, super simplified for the sake of brevity, is setting up your database with a table and its respective attributes (columns), or updating an exisiting table. Its just your way of managing the structure of your database.

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)
  end
end

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
    byebug  
    params[:product].each_with_index do |id, index|
        Product.where(id: id).update_all(position: index + 1)
    end

    head :ok
end

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|
  Post.send_expiration_email
end


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
  end

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|
  begin
    Category.create!(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)
  end
end

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 

request.referrer

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!
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.