Search code examples
ruby-on-railsrubyviewconditional-statements

Ruby on Rails : conditional display


I have just started with Ruby on Rails and I have a use case where I need to map my Json response from a call back into an existing Ruby model. There are a few fields, however, that cannot be mapped directly. I have a resource class looking like this:

class SomeClassResource
  attr_reader :field

def initialize(attrs = {})
  @field = attrs['some_other_field']
end

I have then a method that if some_other_field matches to a specific string then return true, alternatively false, as follows:

  def some_method(value)
    value == 'aString' ? true : false
  end

I then need to display either true or false in my view. What is the correct approach?

Thank you


Solution

  • First off, you should simplify your method to this:

    # app/models/some_class_resource.rb
    def some_method(value)
      value == 'aString'
    end
    

    Then to show it in a view you would want to get the value in a controller first (into an instance variable scoped to the view):

    app/controllers/some_class_resources_controller.rb

    class SomeClassResourcesController << ApplicationController
      def show
        resource       = SomeClassResource.new
        @true_or_false = resource.some_value('aString')
      end
    end
    

    Then you'll want a view with something like this:

    app/views/some_class_resources/show.html.erb

    <h1>My view</h1>
    Was it true? <%= @true_or_false %>
    

    You will also need the appropriate show route in your routes file.

    config/routes.rb

    resources :some_class_resources, only: [:show]