如何在 rails 中访问模型外部的值

How to access a value outside the Model in rails

实际上我有两个模型,产品和类别,类别 ID 作为产品中的外键,我想通过类别 ID 或任何其他方式访问产品 Index.html.erb 中的所有类别,我有以下想法虽然是错误的做法。

<% if  product.category_id == 2 %>
    <td> furniture </td>

    <% elsif  product.category_id == 3 %>
    <td>Animals </td>
    <% else %>
    <td> No category </td>
    <% end %>

她是我的Product_controller.rb

  
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def index
    @products = Product.all
  end


  def show

  end


  def new
    @product = Product.new
  end


  def edit
  end


  def create
    @product = Product.new(product_params)
    @product.user = current_user
    @product.category = Category.first
    
    

  
  
  
  
  private
     actions.
    def set_product
      @product = Product.find(params[:id])
    end

  
    def product_params
      params.require(:product).permit(:productname, :productprice, :productstatus,:image ,:category_id )
    end

当您在模型中正确声明 associations 时 – 类似于此

class Product < ApplicationRecord
  belongs_to :category
end

class Category < AppicationRecord
  has_many :products
end

那么您应该可以只使用 product.category 来加载产品的类别。假设一个类别有类似 name 的内容,那么您的视图可以简化为如下所示:

<td><%= product.category&.name || 'No category' %></td>