Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails中访问模型之外的值_Ruby On Rails_Ruby_Ruby On Rails 6 - Fatal编程技术网

Ruby on rails 如何在rails中访问模型之外的值

Ruby on rails 如何在rails中访问模型之外的值,ruby-on-rails,ruby,ruby-on-rails-6,Ruby On Rails,Ruby,Ruby On Rails 6,实际上我有两个模型,Products&Category,Category id作为产品的外键,我想通过Category id或任何其他方式访问product Index.html.erb中的所有类别,我有以下想法,尽管这是一种错误的方法 <% if product.category_id == 2 %> <td> furniture </td> <% elsif product.category_id == 3 %>

实际上我有两个模型,Products&Category,Category id作为产品的外键,我想通过Category id或任何其他方式访问product 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 %>
当您在模型中正确地声明

class Product < ApplicationRecord
  belongs_to :category
end

class Category < AppicationRecord
  has_many :products
end

创建表“类别”,force::cascade do | t | t.string“name”t.datetime“created|u at”,精度:6,null:false t.datetime“updated|at”,精度:6,null:false end这是我的表,但当我应用时,会出现一个错误,如nil:nilclass的未定义方法'name',这意味着您的数据库中至少有一个产品没有类别我会更新我的答案。
<td><%= product.category&.name || 'No category' %></td>