I’ve been working on a Rails application and am trying to implement the Model-View-Controller (MVC) pattern properly, but I’m running into an issue with my model and controller interaction. I’ve created a model class for my Product
, but when I try to use it in the controller to display data on the view, it doesn’t seem to be showing any records from the database. I’ve checked my database, and the records are there, but I’m not sure if I’m missing something in my controller or model setup. I’ve been following the Rails API documentation: web.api.rubyonrails.org/ Here’s the basic setup I have:
Model:
class Product < ApplicationRecord
validates :name, presence: true
validates :price, presence: true
end
Controller:
class ProductsController < ApplicationController
def index
@products = Product.all
end
end
View (index.html.erb):
<% @products.each do |product| %>
<p><%= product.name %> - <%= product.price %></p>
<% end %>
When I visit the /products
page, the page loads but it doesn’t display any product names or prices. I’ve confirmed that the database contains records, but I can’t figure out why the @products
instance variable isn’t populating in the view.
Has anyone encountered a similar issue? Could this be something related to ActiveRecord or how Rails is handling the database connection? Any help would be greatly appreciated!