【发布时间】:2011-11-20 21:55:42
【问题描述】:
我正在开发一个应用程序,用户的“项目”可以跟踪数据库中的“植物”对象。当我为我的应用程序中的任意数量的植物对象点击“关注”时,我在“关系”控制器(将用户的项目连接到固定的“植物”对象的植物关系)中的创建操作收到以下错误:
“当你没有预料到它时,你有一个 nil 对象! 您可能期望有一个 Array 的实例。 评估 nil 时发生错误。[]"
我意识到这是一个大问题,是的,我几乎是个新手。所有的迁移都应该没问题。我很感激任何帮助——即使这意味着提出一种解决这个问题的全新方法。
这是我的控制器(称为“Prelationships”)的样子:
class PrelationshipsController < ApplicationController
def create
@plant = Plant.find(params[:prelationship][:pfollowed_id])
@project.follow!(@plant)
respond_to do |format|
format.html { redirect_to @project }
format.js
end
end
end
还有我的“关系”模型:
class Prelationship < ActiveRecord::Base
attr_accessible :pfollowed_id
belongs_to :pfollower, :class_name => "Project"
belongs_to :pfollowed, :class_name => "Plant"
validates :pfollower_id, :presence => true
validates :pfollowed_id, :presence => true
end
还有我的“项目”模型:
class Project < ActiveRecord::Base
attr_accessible :title, :address, :latitude, :longitude, :state
belongs_to :user
has_many :prelationships, :foreign_key => "pfollower_id",
:dependent => :destroy
has_many :pfollowing, :through => :prelationships, :source => :pfollowed
def pfollowing?(pfollowed)
prelationships.find_by_pfollowed_id(pfollowed)
end
def pfollow!(pfollowed)
prelationships.create!(:pfollowed_id => pfollowed.id)
end
end
还有我的“植物”模型:
class Plant < ActiveRecord::Base
has_many :prelationships, :foreign_key => "pfollowed_id",
:class_name => "Prelationship"
has_many :pfollowers, :through => :reverse_prelationships,
:source => :pfollower
end
最后,我的“_plants_form”部分视图:
<%= form_for @project.prelationships.build(:pfollowed_id =>
@project_id) do |f| %>
<%= collection_select(:prelationships, :pfollowed_id, Plant.all, :id, :name,
options = {:prompt => "Select your plants"}, :class => "listselect") %>
<div class="actions"><%= f.submit "Pfollow" %></div>
<% end %>
这是我日志中的错误:
Started POST "/prelationships" for 127.0.0.1 at 2011-11-20 23:31:57 +0100
Processing by PrelationshipsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"NKqa1f0M2yPLQDHbRLnxl3SiwBeTus/1q1hpZjD7hgY=",
"prelationships"=>{"pfollowed_id"=>"5"}, "commit"=>"Pfollow"}
Completed 500 Internal Server Error in 14ms
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]):
app/controllers/prelationships_controller.rb:4:in `create'
Rendered /Users/mmelone12/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-
3.0.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.4ms)
Rendered /Users/mmelone12/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-
3.0.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(30.6ms)
Rendered /Users/mmelone12/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-
3.0.9/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within
rescues/layout (37.1ms)
【问题讨论】:
-
能贴一下错误的回溯吗?
-
如果您需要其他帮助破解此问题,请告诉我
-
@project在哪里被实例化?
标签: ruby-on-rails ruby-on-rails-3 rails-activerecord relationship