获取图像以显示在具有多个/属于关系的Rails中

时间:2016-05-13 20:01:34

标签: ruby-on-rails activerecord has-many

我正在尝试在此食谱索引页面上显示图像。此时我有一个食谱模型,一个用户模型和一个图像模型。我有属于食谱模型的图像模型,食谱模型有很多图像。用户模型通过配方模型有很多图像。

我从终端获得的错误是来自nilClass的未定义方法'url'。 Url是我的图像表上的已定义字段。如果我在索引中运行recipe.images,我会在页面上显示损坏的图像链接。这是.url无效。

以下是我的模特

首先是图像

  class Image < ActiveRecord::Base
    belongs_to :recipe
  end

这是用户

class User < ActiveRecord::Base

  has_many :recipes

  has_many :images, through: :recipes

end

这是食谱

class Recipe < ActiveRecord::Base

  belongs_to :user

  has_many :images

end

这是通过食谱控制器

设置的索引视图页面
<h1>Recipes</h1>

<% @recipes.each do |recipe| %>
  <h2><%= recipe.name %></h2>
  <a href="/recipes/<%= recipe.id %>"> <img src="<%= recipe.images.first.url %>" alt="<%= recipe.name %>"></a>
  <p>Cooktime:<%= recipe.cooktime %>
  Serves:<%= recipe.amount %></p>
  <p>Description:<%= recipe.description %></p>

<% end %>

最后这里是食谱控制器

class RecipesController < ApplicationController

  def index

    @recipes = Recipe.all

  end

  def new

    @recipe = Recipe.new

  end

  def create

    @recipe = Recipe.create({
      name: params[:name],
      description: params[:description],
      ingredients: params[:ingredients],
      directions: params[:directions],
      amount: params[:amount],
      cooktime: params[:cooktime],
      favorite: params[:favorite],
      user_id: params[:user_id],
      })
    Image.create({
      url: params[:image],
      recipe_id: @recipe.id
      })

    render :show

  end

  def show

    @recipe = Recipe.find(params[:id])

  end

  def edit

    @recipe = Recipe.find(params[:id])

  end

  def update

    @recipe = Recipe.find(params[:id])

    @recipe.update({
      name: params[:name],
      description: params[:description],
      ingredients: params[:ingredients],
      directions: params[:directions],
      amount: params[:amount],
      cooktime: params[:cooktime],
      favorite: params[:favorite],
      user_id: params[:user_id]
      })

    render :show

  end

  def destroy

    @recipe = Recipe.find(params[:id])
    @recipe.destroy

    redirect_to "/recipes"

  end

end

0 个答案:

没有答案