Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - Check If Child Id Exists Within Record of HABTM Relationship

I have a set of resources called Tasks and Posts and there are in a has_and_belongs_to_many (HABTM) relationship with each other.

There is also a join table connecting their values.

create_table 'posts_tasks', :id => false do |t|
   t.column :post_id, :integer
   t.column :task_id, :integer
end

So my question is how do I check to see if the id of a specific task exists within the array created from @post.tasks?

irb(main):011:0> @post = Post.find(1)
=> #<Post id: 2, comment: "blah blah", created_at: "2011-10-18 03:40:30", updated_at:
irb(main):012:0> @post.tasks
=> [#<Task id: 1, description: "Test 1", created_at: "2011-10-18 03:
   22:05", updated_at: "2011-10-18 03:22:05">, #<Task id: 3, description: "Test 3",
   created_at: "2011-10-18 03:22:21", updated_at: "2011-10-18 03:22:21
    ">]

So my question is whats the ruby way for writing does "@task = Task.find(2)" exist within @post.tasks and if so return true or false?

like image 867
ChrisWesAllen Avatar asked Oct 18 '11 03:10

ChrisWesAllen


1 Answers

@post.tasks.where(:id => task_id).present?

Is much lighter compared to what Gabelsman has suggested.

like image 169
Chirantan Avatar answered Oct 22 '22 16:10

Chirantan