Rails Object Relationships and JSON Rendering

By default you’ll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well: def export @export_data = ModelA.find(params[:id]) respond_to do |format| format.html format.json { render :json => @export_data.to_json(:include => :modelb) } end end You can even tell it to exclude certain … Read more

how to delete a job in sidekiq

According to this Sidekiq documentation page to delete a job with a single id you need to iterate the queue and call .delete on it. queue = Sidekiq::Queue.new(“mailer”) queue.each do |job| job.klass # => ‘MyWorker’ job.args # => [1, 2, 3] job.delete if job.jid == ‘abcdef1234567890’ end There is also a plugin called sidekiq-status that … Read more

How to do static content in Rails?

For Rails6, Rails5 and Rails4 you can do the following: Put the line below at the end of your routes.rb get ‘:action’ => ‘static#:action’ Then requests to root/welcome, will render the /app/views/static/welcome.html.erb. Don’t forget to create a ‘static’ controller, even though you don’t have to put anything in there. Limitation: If somebody tries to access … Read more

Rails: Order with nulls last

I’m no expert at SQL, but why not just sort by if something is null first then sort by how you wanted to sort it. Photo.order(‘collection_id IS NULL, collection_id DESC’) # Null’s last Photo.order(‘collection_id IS NOT NULL, collection_id DESC’) # Null’s first If you are only using PostgreSQL, you can also do this Photo.order(‘collection_id DESC … Read more

Specifying column name in a “references” migration

For Rails 5+ Initial Definition: If you are defining your Post model table, you can set references, index and foreign_key in one line: t.references :author, index: true, foreign_key: { to_table: :users } Update Existing: If you are adding references to an existing table, you can do this: add_reference :posts, :author, foreign_key: { to_table: :users } … Read more