开发者

Parent model method is undefined

开发者 https://www.devze.com 2023-03-27 16:12 出处:网络
I\'m an absolute beginner to Ruby on Rails; I literally started last night.I\'m following the Getting Started with Rails tutorial, although I\'ve made a few modifications.Instead of a blog with posts

I'm an absolute beginner to Ruby on Rails; I literally started last night. I'm following the Getting Started with Rails tutorial, although I've made a few modifications. Instead of a blog with posts and comments, I'm making a simple task-tracking application in which Projects have Tasks associated with them.

Everything was going quite well until step #9 (Deleting Comments). According to the tutorial, I should be able to get the parent model for a comment by calling comment.post, the analogue of which in my case is task.project. But when Rails tries to render the partial in which I've got task.project, it raises a NoMethodError:

undefined method `project' for #<Task:0x7fb0011cf058>

My models are as follows:

class Project < ActiveRecord::Base
  validates :name, :presence => true

  has_many :tasks, :dependent => :destroy
end

class Task < ActiveRecord::Base
  validates :name, :presence => :true

  belongs_to :project
end

Using the rails console, I determined that my tasks do have a project_id method which returns the ID of the associated project. Thus, I can get around the problem by using Project.find(task.project_id) instead of task.project in my partial. That seems "wrong," though, and makes me wonder if the relationship between my two models is somehow broken.

What's going on here?

Update: If I comment out the validates line in the Task model, then all of its methods work properly. I don't understand why that is the case, though.

Update 2: Figured it out. I was using the 开发者_StackOverflow中文版symbol :true instead of the simple boolean value in the validates line of my Task model. Had I paid more attention to the stack trace in the first place, I would have figured it out much sooner. What an embarrassing mistake!


Your code looks perfect. But if you were trying that into console try reloading first and then try again

reload!
task = Task.find(<record-id>)
task.project

It should be working.

0

精彩评论

暂无评论...
验证码 换一张
取 消