Не удается получить доступ к атрибутам из связанных рельсов модели - PullRequest
0 голосов
/ 24 декабря 2018

У меня есть три модели: ингридиент, recipe_ingredient и recey

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 Showиз контроллера получателей:

def show
 @recipe_ingredients = @recipy.recipe_ingredients
end

Но я получаю следующее сообщение об ошибке: неопределенный метод `ing_name 'для nil: NilClass

Мои ингредиенты:

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

Кажется, это работает так:

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

Но это не использует связь между таблицами, если я правильно понимаю?Любая помощь?Благодаря.

Ответы [ 2 ]

0 голосов
/ 24 декабря 2018

проблема в том, что внутри вашего метода показа @recipy - ноль, здесь обычно код для контроллера

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

view

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

Я бытакже добавьте некоторые предложения к своим модельным отношениям следующим образом, поскольку Ingredient и 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
0 голосов
/ 24 декабря 2018

У вас есть ингредиент 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 это чтобы избежать этой нулевой ошибки (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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...