【问题标题】:Cannot access attributes from associated model rails无法从关联的模型导轨访问属性
【发布时间】:2018-12-24 14:44:13
【问题描述】:

我有三个模型,成分,recipe_ingredient 和 recipy

class Ingredient < ApplicationRecord
  has_many :recipe_ingredients
end

class RecipeIngredient < ApplicationRecord
 belongs_to :recipy, :dependent => :destroy
 belongs_to :ingredient
end

class Recipy < ApplicationRecord
  has_many :recipy_steps
 has_many :recipe_ingredients, :dependent => :delete_all
end

我正在尝试从食谱显示页面访问成分表中的 ing_name 属性。

<% @recipe_ingredients.each do |ing| %>
<p> <%= ing.amount  %> <%= ing.unit %>
<%= ing.ingredient.ing_name %>
</p>

从recipies 控制器中显示:

def show
 @recipe_ingredients = @recipy.recipe_ingredients
end

但我不断收到以下错误消息: nil:NilClass 的未定义方法“ing_name”

我的成分参数:

def ingredient_params
params.require(:ingredient).permit(:ing_name)
end

它似乎确实像这样工作:

    <%= Ingredient.where(id: ing.ingredient_id).pluck(:ing_name) %>

但是,如果我理解正确,这不会使用表之间的连接吗?有什么帮助吗?谢谢。

【问题讨论】:

  • 您遇到的错误是什么
  • 。 nil:NilClass 的未定义方法 `ing_name' 但已解决

标签: ruby-on-rails database


【解决方案1】:

你有成分 nil 这就是你得到错误的原因。

必须是你的控制器有一些 before_action 钩子来加载 recipy

class RecipesController < ApplicationController
  before_action :load_recipy, only: :show

  def show
    @recipe_ingredients = @recipy.recipe_ingredients
  end

 private
 def load_recipy
   @recipy = Recipy.find(params[:id])
  end
end

你可以try这个来避免这个nil错误(undefined method 'ing_name' for nil:NilClass)

<% @recipe_ingredients.each do |ing| %>
<p> <%= ing.amount  %> <%= ing.unit %>
<%= ing.try(:ingredient).try(:ing_name) %>
</p>

默认情况下,从 Rails 5 中,您有一个 required 选项来使成分始终不是 nullable

如下图

belongs_to :ingredient, required: true

也会防止出现这种错误

class RecipeIngredient < ApplicationRecord
 belongs_to :recipy, :dependent => :destroy
 belongs_to :ingredient, required: true
end

【讨论】:

  • 非常感谢,现在效果很好!我实际上尝试过它是否只适用于如下一次尝试: 似乎没问题。再次感谢!
【解决方案2】:

问题是因为在你的 show 方法中 @recipy 是 nil, 这里通常是 show 的代码

控制器

def show
  @recipy = Recipy.find(params[:id]) # --> you missed this line
  @recipe_ingredients = @recipy.recipe_ingredients # @recipy will be null without line above
end

查看

<% @recipe_ingredients.each do |ing| %>
  <p> <%= ing.amount  %> <%= ing.unit %> <%= ing.ingredient.ing_name %> </p>
<% end %>

我还想为您的模型关系添加一些建议,如下所示,因为成分和 Recipy 显示了多对多关系

class Ingredient < ApplicationRecord
  # -> recipe_ingredients -> recipies
  has_many :recipe_ingredients, :dependent => :destroy
  has_many :recipies, through: :recipe_ingredients
end

class RecipeIngredient < ApplicationRecord
 belongs_to :recipy
 belongs_to :ingredient
end

class Recipy < ApplicationRecord
  has_many :recipy_steps
  # -> recipe_ingredients -> ingredients
  has_many :recipe_ingredients, :dependent => :destroy
  has_many :ingredients, through: :recipe_ingredients
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 2016-08-15
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多