开发者

Simple if statement question for record not found

开发者 https://www.devze.com 2023-04-08 23:00 出处:网络
I\'ve got the following statement: @all_c开发者_Python百科omments = Comment.find(@task.id) The problem is, if there are no comments it throws a record not found error. How can I get this to fail si

I've got the following statement:

@all_c开发者_Python百科omments = Comment.find(@task.id)

The problem is, if there are no comments it throws a record not found error. How can I get this to fail silently, so it just returns nothing?


what you are trying to do can never work.

The line find(@task.id) will look for comments that have the same id as the task which is normally not how you set up relations.

Normally you would have a task, and a comments table, and the comments table would have a column called task_id. If that is the case, you could write your models as follows:

class Task
  has_many :comments
end

class Comment
  belongs_to :task
end

and then you can simply write:

@all_comments = @task.comments


I don't use AR, but I believe just:

@all_comments = Comment.find(:first, @task.id)

will return nil if there is no record found, unlike #find without any modifiers.

EDIT | There's a shortcut too:

@all_comments = Comment.first(@task.id)


I think that your failure is a different one you expect. Your query asks for a Comment with the ID @task.id (which is the ID of the Task).

Your query should go like that:

@all_comments = Comment.where(:task_id => @task.id)

or even better

@task.comments

This should work if you have declared your relations accordingly, and allows some more options (adding comments, ...).

Have a look at the "Rails Guides", and there the "Active Record Query Interface".


The rails throws RecordNotfound exception for find calls. Use find_by calls to avoid this.

If you are trying to get a list of tasks by task_id then user the find_all_by method:

# returns an empty array when no tasks are found
@comments = Comment.find_all_by_task_id(@task.id)

Otherwise use find_by

# returns nil when no task is found
@comment = Comment.find_by_task_id(@task.id)
0

精彩评论

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