我有用户模型,事件模型,事件优先级模型和事件类型模型。型号代码如下:
class Event < ActiveRecord::Base
belongs_to :user
belongs_to :event_priority
belongs_to :event_type
attr_accessible :name, :raised_date, :location, :description, :longtitude, :latitude
attr_protected :raised_user_id, :event_priority_id, :event_type_id
end
class EventPriority < ActiveRecord::Base
has_many :events
has_many :users, :through => :events
has_many :event_types, :through => :events
end
class EventType < ActiveRecord::Base
has_many :events
has_many :users, :through => :events
has_many :event_priorities, :through => :events
end
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :first_name, :last_name, :full_name, :password, password_confirmation
has_many :events, :foreign_key => "raised_user_id", :dependent => :destroy
has_many :event_priorities, :through => :events
has_many :event_types, :through => :events
end
在下面的rails控制台示例中,有人能解释无法从事件返回到用户吗?
irb(main):027:0> @user = User.find(2)
=> Returns the user with an ID of 2.
irb(main):028:0> @user.events
=> Returns all events for that user.
irb(main):029:0> @user.events.first.user
=> nil --HUH????
irb(main):031:0> @event = @user.events.first
=> Saves and returns the first event created by the user.
irb(main):032:0> @event.user
=> nil --Again, WHY??
irb(main):033:0> @events = Event.all
=> Saves and returns all events.
irb(main):035:0> @events.first.user
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.first
from (irb):35
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0.
6/lib/active_model/attribute_methods.rb:279 -- AGAIN, WHY?
答案 0 :(得分:1)
您是否有充分的理由不仅使用user_id
作为events
表中的外键? (这就是造成问题的原因)
尝试在Event类中添加foreign_key
选项
答案 1 :(得分:0)
您可以从用户转到事件,因为您已告知“用户has_many事件”关联以使用您的自定义外键。你无法回来,因为你没有告诉“Event belongs_to User”关联使用该自定义密钥。因此它需要“user_id”的默认密钥,它无法找到,因此它无法返回。
我很惊讶它优雅地处理它(通过返回nil),实际上 - 我希望它在那时抛出异常。
我恐怕我不知道你的第二个问题。我只能猜测你在错过的IRB行#34上以某种方式将@events
设置为nil
...
希望有所帮助!