How to pass hash data in rails view?

125 Views Asked by At

I'm facing the issue

undefined local variable or method `student_details'

while trying to write a Ruby method that gives dynamic data to display in the browser. I've used view_component gem. My "component.rb" file looks like following:

module Shared
  module Student
    class Component < ViewComponent::Base
      def initialize(title:)
        @title = title
      end
      student_details = {name: "John Doe", course: "Rails Development", student_id: "1"}
    end
  end
end

And "component.html.erb" looks as:

<div class="font-montserrat flex flex-col bg-white text-shadow-none">  
  <%= student_details.student_id %>
  <%= student_details.name %>
  <%= student_details.course %>
</div>
1

There are 1 best solutions below

0
sassyg On

The data is only accessible via instance variables (@var) or ruby methods (def method). You could do this with the variable:

module Shared
  module Student
    class Component < ViewComponent::Base
      def initialize(title:)
        @title = title
        @student_details = {name: "John Doe", course: "Rails Development", student_id: "1"}

      end
    end
  end
end

or this with a method

module Shared
  module Student
    class Component < ViewComponent::Base
      def initialize(title:)
        @title = title
      end

      def student_details
        {name: "John Doe", course: "Rails Development", student_id: "1"}
      end
    end
  end
end