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?
@post.tasks.where(:id => task_id).present?
Is much lighter compared to what Gabelsman has suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With