簡體   English   中英

無法從關聯的模型導軌訪問屬性

[英]Cannot access attributes from associated model rails

我有三種模型,成分,配方成分和配方

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>

def從收款控制器顯示:

def show
 @recipe_ingredients = @recipy.recipe_ingredients
end

但是我一直收到以下錯誤消息:nil:NilClass的未定義方法“ ing_name”

我的Ingredient_params:

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

它看起來確實像這樣工作:

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

但是,如果我理解正確的話,這不會使用表之間的連接嗎? 有什么幫助嗎? 謝謝。

您有nil成分,這就是為什么您出錯了。

必須是您的控制器具有一些before_action鈎子才能加載配方

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

問題是因為在您的show方法@recipy內部為零,這通常是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 %>

我還想向您的模型關系添加一些建議,因為成分和配方顯示了多對多關系

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM