Jacob Montgomery

Joined

34,500 Experience
33 Lessons Completed
41 Questions Solved

Activity

Posted in uninitialized constant User::shift

Look at your foreign/primary key assignments on your Shift model, that should be:

belongs_to :user, foreign_key: 'guid', primary_key: 'user_guid'

After you adjust the foreign/primary key names if it still doesn't work, double check your model file names and their class declarations to ensure there's no typos.

Another thing I just noticed, are your models inheriting from ApplicationRecord? Your code doesn't show that to be the case. They should be:

class Shift < ApplicationRecord
  ...
end

and

class User < ApplicationRecord
  ...
end

Posted in how do i solve this

Hey Vwareken,

Check out the guide here: https://gorails.com/setup/ubuntu/18.10

I'm not familiar with Linux Lite OS, but a quick glance looks like its based on Ubuntu LTS so those guides should be good to follow.

Posted in uninitialized constant User::shift

Hey geekdie,

At a glance, try removing class_name from both of your associations. There's no need to do that (as far as I'm aware) unless the class name is different than the name you want to use when calling the association.

Posted in Chart Size Convert

Hey Emrah,

I'm not really sure what you're after, did you try it? What was the error?

See the docs - https://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human_size

Haha, yeah it can be fun trying to figure out some of the little nuances...

For your routing, check out scopes which will let you do things like:

namespace :admins do
  scope module: :locations do
    scope ':location_id' do
      resources :discounts
    end
  end
end

Which would give routes like /admins/:location_id/discounts and /admins/:location_id/discounts/:id/edit

Hey Alan,

I think the before_methodis the way to go here if all you're needing to do is see if the current_user is part of the requested group.

  def authenticate_group_access
    unless current_user.groups.pluck(:id).include?(params[:group_id])
      redirect_back fallback_location: some_default_path, notice: "Silly bloke, you can't do that!"
    end
  end

There may be a cleaner way to handle the changing group_id param, but the few times this problem has popped up I break the rails convention (gasp!) and update my routes to use :group_id instead of :id since you have nested resources. Really I kind of prefer the more explicit convention of :model_id over the more ambigious :id for this very reason. It does require you to pay a bit more attention to your links and such.

Hey James,

How exactly are you running this rake command in production? Are you using cron to manage or..?

I copied your code the other day when it was still at 42 and it looks like over night it updated again to to now be 43. When I run my copy here, it shows the updated count as expected... so I have a feeling it has to be something with how its implimented in your production environment that's causing the issue.

Posted in How to Add Pagination with Pagy Discussion

Hey Stan X,

Check out the pagy_searchkick extra - https://ddnexus.github.io/pagy/extras/searchkick

Posted in Non-series episode list?

Is this what you mean? https://gorails.com/episodes

Posted in Check a user is author of post before edit or delete

Hey Philip,

Yes, that's fine to do.

I personally prefer to just check by @post.user_id as opposed to @post.user as it will most likely have to hit the DB to fetch the user object, whereas @post.user_id == current_user.id won't need to.

Posted in Inheritance is not working.

Hey leroydupuis,

To get the result you're after, remove TimeLine.new([1,2,3,4]) and instantiate AuthenticateTimeLine with the array instead

authenticate_timeline = AuthenticateTimeLine.new([1,2,3,4])
authenticate_timeline.print

You don't create the parent object and then create the child object, the child object inherits from the parent object so you just work from the child. There are way better / more scholarly explanations for all this than what I can regurgitate, just Google ruby inheritance and keep playing around with it, you're 99% there.

Posted in How do I query a model with a value less than

If I'm not mistaken, order is a reserved keyword in most DB's, I know it is in PG.

Quick test I got the same result as you, but my foo column returned fine.

Rename your column order to something else, maybe position and then you should be good to go.

Posted in Load only products based on region ideas please :)

Aye, I agree - if SEO makes no difference then keep the URL's simple.

I suppose the only other thing to consider is could the URL's be sharable? If that matters at all then you may consider using both cookies and params so if a user shares the URL it will present the correct info.

This is where you may want to rearrange the ternary operation and put params.key?(:region_id) before current_user.region_id and cookies.key?(:region_id) so if the user is signed in and receives a link from someone else the proper results will display.

Posted in Load only products based on region ideas please :)

Hey Alan!

Does SEO matter at all here? If so then you could utilize slugs for the :region_id so it's site.com/texas/austin/products instead of site.com/texas/13/products.

A cookie would be useful if you want there to be any sort of persistence between sessions or between page navigations. So you could do a few checks

region_id = cookies.key?(:region_id) ? cookies[:region_id] : params[:region_id]
region_id.present? ? Region.find_by_region_id(region_id) : Region.all

If this is after a user signs in, then you could also persist their region selection in the user object and check for that as well... just be sure you put things in order of precedence

region_id = current_user.region_id.present? ? current_user.region_id : cookies.key?(:region_id) ? cookies[:region_id] : params[:region_id]
region_id.present? ? Region.find_by_region_id(region_id) : Region.all

Then if you want to reset it to a default value after they sign out then just be sure to reset it during the destroy session method.

Cheers! :)

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

Aye no problem!

As for your other problem, you could use the strip_tags helper strip_tags(@post.content) which should take care of any basic HTML. You could also create a new column, something like intro_text that would allow you to display that text instead and reserve the content for the full blog post. If you decide to use strip_tags, take a look at the truncate helper as well since you'll probably want to truncate the text at some point and provide a "read more" link.

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

  • date_field is correct i think

Doh, you're right. I read through the schema too fast and mis-read the field. Sorry for the confusion. Although you may consider renaming it publish_date or something a little less ambiguous.

app/models/image.rb you need to include optional: true on your belongs_to :post declaration (sorry that was my fault, I forgot to add it to the gist). I bet if you look in your logs as you try to attach an image you'll get an error saying post_id is missing. As of Rails 5, belongs_to associations must have an association ID on save. However, for your situation that doesn't jive, so you need to add the optional flag so it can save. I bet this is why you're not getting any images saved. - see: https://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html

  • Did i implemented the js correct?

Looks right to me, I'm 99% certain the optional: true flag is what's causing your problem right now.

  • And did the images from the posts still should show up like normal in all_weeks where i call the content?

Yes, you'll still have the embedded image in your post as before, just now you also have an association to those image objects so you can display images without having to also display the contents of the blog post. So if all you want to display is the title of the blog post and the first image, you can do that now with @post.title and @post.images.first.image_url

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

Ah, ok one thing I forgot to include in the gist was the update to your images controller so it returns the ID... so in app/controllers/images_controller.rb you need to change:

format.json { render json: { url: @image.image_url }, status: :ok }

to

format.json { render json: { image_id: @image.id, url: @image.image_url }, status: :ok }

So that's one thing...

Oh, another I forgot was you need to rename a few things... we're going to stick with the convention images instead of photos since you mainly use images. So your app/uploaders/photo_uploader.rb needs to be renamed to app/uploaders/image_uploader.rb and also update the class inside from PhotoUploader to ImageUploader. Now head over to your Image model and change the include from include ::PhotoUploader::Attachment.new(:image) to include ::ImageUploader::Attachment.new(:image) and that should fix your upload problems.


Another I just noticed while looking at the repo was in app/controllers/posts_controller.rb in your index action, you have:

def index
  @posts = Post.all
  @posts = Post.order(date_field: :desc)
end

Just update it to:

def index
  @posts = Post.order(created_at: :desc)
end

I assume date_field is just a copy/paste error from the group_date gem. Also, since you are now needing the images when you display them on the index, you may consider using includes so the association is loaded with includes(:images) ... so now your index action would be @posts = Post.order(created_at: :desc).includes(:images). This just helps speed things up a bit, probably won't be noticeable for such a simple setup but it's a good habit to get into.


Let me know how that works - also note that any of your old posts + images aren't going to be associated since the association is made at the time of saving the post. So you'll have to manually make those associations if there's any. If there are, just add the respective post_id value to the image.

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

Sorry if multiple posts are happening, everytime I paste my reply and save, it eats it up and isn't showing as being posted on my end.

Shortening it down and attaching the bulk as a github gist -


I should have paid a bit more attention to the actual Trix implementation...

The Trix editor is uploading the images and creating the Photo object as soon as you drag + drop them into the text area. The problem is your Post hasn't been saved yet, which means it doesn't have an ID so you can't associate the Image to the Post at the database level.

Here's the gist with the rest: https://gist.github.com/nanosplit/585cb1776422199e3fce7b7ed4dae615

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

Ahhh ok, I should have paid a bit more attention to the actual Trix implementation.

The Trix editor is uploading the images and creating the Photo object as soon as you drag + drop them into the text area. The problem is your Post hasn't been saved yet, which means it doesn't have an ID so you can't associate the Image to the Post at the database level.

There's probably a few ways to handle this, one off the top of my head would be to first add post_id to the Image model.

rails g migration addPostIdToImages post:references

which should give you

class AddPostToImages < ActiveRecord::Migration[5.2]
  def change
    add_reference :images, :post, foreign_key: true
  end
end

Then add your associations to your Post and Image models

class Post < ApplicationRecord
  has_many :images
end

class Image < ApplicationRecord
  belongs_to :post
end

Now you need to have the xhr request return the ID of each saved photo and load it into an array to be passed with the post attributes upon save. To do this, you need to first create a hidden field to hold the array of image_ids

app/views/posts/new.html.erb (you really should be using the _form.html.erb partial, but this is based on your repo)

<%=form_for @post do |form| %>
  ...
  <%= form.hidden_field :image_ids %>
  ...
<% end %>

then update trix_attachments.js to update the value of the hidden field on each upload

app/assets/javascripts/trix_attachments.js

xhr.onload = function() {
  if (this.status >= 200 && this.status < 300) {
    var data = JSON.parse(this.responseText);

    var image_ids_input = $("#post_image_ids");
    var image_ids = image_ids_input.val() ? JSON.parse(image_ids_input.val()) : []
    image_ids.push(data.image_id);
    image_ids_input.val(JSON.stringify(image_ids));

    return attachment.setAttributes({
      url: data.url,
      href: data.url,
    });
  }
};

In your post create action, you could take those ID's and assign them to the images

def create
  @post = Post.new(post_params)

  if @post.save
    image_ids = params['post']['image_ids']
    image_ids = image_ids.present? ? JSON.parse(image_ids) : nil
    if image_ids.present?
      Image.where(id: image_ids).update_all(post_id: @post.id)
    end

    redirect_to posts_path
  else
    render "new"
  end
end

Now you can get your images by its association with images, and since you want a random image, you can do

app/views/posts/index.html.erb

<% @posts.each do |post| %>
  ...
  <%= image_tag post.images.offset(rand(post.images.count)).first.image_url if post.images.present? %>
  ...
<% end %>

which will select one random image and display it if there are any attached images to that post.

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

Ahhh ok, I should have paid a bit more attention to the actual Trix implementation.

The Trix editor is uploading the images and creating the Photo object as soon as you drag + drop them into the text area. The problem is your Post hasn't been saved yet, which means it doesn't have an ID so you can't associate the Image to the Post at the database level.

There's probably a few ways to handle this, one off the top of my head would be to first add post_id to the Image model.

rails g migration addPostIdToImages post:references

which should give you

class AddPostToImages < ActiveRecord::Migration[5.2]
  def change
    add_reference :images, :post, foreign_key: true
  end
end

Then add your associations to your Post and Image models

class Post < ApplicationRecord
  has_many :images
end

class Image < ApplicationRecord
  belongs_to :post
end

Now you need to have the xhr request return the ID of each saved photo and load it into an array to be passed with the post attributes upon save. To do this, you need to first create a hidden field to hold the array of image_ids

app/views/posts/new.html.erb (you really should be using the _form.html.erb partial, but this is based on your repo)

<%=form_for @post do |form| %>
  ...
  <%= form.hidden_field :image_ids %>
  ...
<% end %>

then update trix_attachments.js to update the value of the hidden field on each upload

app/assets/javascripts/trix_attachments.js

xhr.onload = function() {
  if (this.status >= 200 && this.status < 300) {
    var data = JSON.parse(this.responseText);

    var image_ids_input = $("#post_image_ids");
    var image_ids = image_ids_input.val() ? JSON.parse(image_ids_input.val()) : []
    image_ids.push(data.image_id);
    image_ids_input.val(JSON.stringify(image_ids));

    return attachment.setAttributes({
      url: data.url,
      href: data.url,
    });
  }
};

In your post create action, you could take those ID's and assign them to the images

def create
  @post = Post.new(post_params)

  if @post.save
    image_ids = params['post']['image_ids']
    image_ids = image_ids.present? ? JSON.parse(image_ids) : nil
    if image_ids.present?
      Image.where(id: image_ids).update_all(post_id: @post.id)
    end

    redirect_to posts_path
  else
    render "new"
  end
end

Now you can get your images by its association with images, and since you want a random image, you can do

app/views/posts/index.html.erb

<% @posts.each do |post| %>
  ...
  <%= image_tag post.images.offset(rand(post.images.count)).first.image_url if post.images.present? %>
  ...
<% end %>

which will select one random image and display it if there are any attached images to that post.

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.