Rails: Render view from outside controller

Rails 5 and 6 support this in a much more convenient manner that handles creating a request and whatnot behind the scenes: rendered_string = ApplicationController.render( template: ‘users/show’, assigns: { user: @user } ) This renders app/views/users/show.html.erb and sets the @user instance variable so you don’t need to make any changes to your template. It automatically … Read more

Ruby: substring to a certain length and also to last whitespace within substring

If you’re using Rails 4+ you should just use the built-in truncate helper method, e.g.: <%= truncate item.description, length: 30, separator: /\w+/ %> The string “…” will be appended to truncated text; to specify a different string, use the :omission option, e.g. omission: “xxx”. For Rails 3.x the :separator option must be a string. Giving … Read more

Upgrading to devise 3.1 => getting Reset password token is invalid

You commented on my similar question a bit ago, and I found an answer that might help you as well. Upgrading to Devise 3.1.0 left some ‘cruft’ in a view that I hadn’t touched in a while. According to this blog post, you need to change your Devise mailer to use @token instead of the … Read more

ArgumentError (too few arguments): when calling format.json on rails 4.04

Mostly you would get the error ArgumentError (too few arguments): on the format when you forget to call this part of code within the block to respond_to method call. Your code should actually look like def action_name respond_to do |format| ## Add this format.json { render json: {}, status: :ok} format.html ## Other format end … Read more

Rspec/Capybara loading in progress, circular require considered harmful

Remove –warnings from .rspec. The generator in rspec 3.0.0 included this setting, but we’ve realized it was a mistake — while it’s good to encourage users to write warning-free code, it’s confusing for users to get these warnings without being sure why. For more info: https://github.com/rspec/rspec-core/issues/1571

Ruby on Rails 4: Pluck results to hash

You can map the result: Person.all.pluck(:id, :name).map { |id, name| {id: id, name: name}} As mentioned by @alebian: This is more efficient than Person.all.as_json(only: [:id, :name]) Reasons: pluck only returns the used columns (:id, :name) whereas the other solution returns all columns. Depending on the width of the table (number of columns) this makes quite … Read more

warning: toplevel constant referenced

Your folder/file structure should look as follows: app/ models/ question/ document.rb answer.rb document.rb question.rb And then rails will automatically find the correct models (it will translate the model name to a filename, and namespaces are translated to folders). Make sure that inside your question/document.rb the class definition looks as one of the following alternatives: class … Read more