我一直试图找到这个问题的答案,但没有任何运气。我想这是一个关联问题,可能是一个菜鸟错误(我只是一个)。 这是功能: 我需要为特定的配置文件创建一堆啤酒(我知道一切听起来都很有啤酒但是它让我感到害怕)
我有3个型号:
啤酒模特:
class Beer < ActiveRecord::Base
include PermissionsConcern
validates :name, presence: true
has_many :ratings
has_many :users, through: :ratings
has_many :packs
end
个人资料模型:
class Profile < ActiveRecord::Base
has_many :packs
end
包装模型:
class Pack < ActiveRecord::Base
belongs_to :beer
belongs_to :profile
end
这是packs_controller
class PacksController < ApplicationController
before_action :set_pack, only: [:show, :edit, :update, :destroy]
def index
@packs = Pack.all
end
def show
end
def edit
@beers = Beer.all #Implementación incompleta. Revisar Filtros
@profiles = Profile.all
end
def create
@pack = Pack.new(pack_params)
respond_to do |format|
if @pack.save
format.html { redirect_to @pack, notice: 'Pack was successfully created.' }
else
format.html { render :new }
end
end
end
def update
respond_to do |format|
if @pack.update(pack_params)
format.html { redirect_to @pack, notice: 'Pack was successfully updated.' }
else
format.html { render :edit }
end
end
end
...
private
def set_pack
@pack = Pack.find(params[:id])
end
def pack_params
params.require(:pack).permit(:delivery_date, :profile_id, :beer_id, :status)
end
end
使用此配置,我有以下情况:
我在索引视图中
@packs.each do |p|
p.beer.name #works fine
p.profile.name #brings an "undefined method `name' for nil:NilClass" message
end
在节目视图中我做了:
@pack.beer.name #works fine.
@pack.profile.name #WORKS FINE ALSO
我尝试在控制台中执行此操作并且结果相同:
Pack.last.profile.name # works fine
Pack.all # works and shows the profile_id correctly.
packs = Pack.all
packs.each do |p|
print p.beer.name #works fine
print p.profile.name #nil class again
end
以防我包含Schema:
create_table "beers", force: :cascade do |t|
t.string "name", limit: 255
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "beer_type", limit: 255
end
create_table "packs", force: :cascade do |t|
t.date "delivery_date"
t.integer "profile_id", limit: 4
t.integer "beer_id", limit: 4
t.integer "status", limit: 4
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "packs", ["beer_id"], name: "index_packs_on_beer_id", using: :btree
add_index "packs", ["profile_id"], name: "index_packs_on_profile_id", using: :btree
create_table "profiles", force: :cascade do |t|
t.string "ibu_range", limit: 255
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name", limit: 255
end
add_foreign_key "packs", "beers"
add_foreign_key "packs", "profiles"
end
我试图尽可能详细地解释这种情况。谁能帮我理解我做错了什么?感谢!!!
答案 0 :(得分:0)
有些包装可能没有配置文件吗?
由于您使用的是控制台,请尝试以下操作:
Pack.all.select{|item| item.profile.nil?}.size
如果尺寸> 0且您不想这样做,请添加validates :profile, presence: true
。