Stage
Let's talk about the most common type of association we encounter.
I have a user who :has_manyPost (s)
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
Problem Statement
I want to do some (very easy and fast) processing on all user posts. I am looking for the best way to structure my code to achieve it. Below are a few ways and why they work or do not work.
Method 1
Do it in the class itself User.
class User < ActiveRecord::Base
has_many :posts
def process_posts
posts.each do |post|
end
end
end
The post class remains the same:
class Post < ActiveRecord::Base
belongs_to :user
end
This method is called:
User.find(1).process_posts
Why is this not the best way to do this
- Post. :has_many , . orders, comments, children ..
User process_orders, process_comments, process_children (yikes), , ( ) , .. .
2
-
/ User, . , all .
3
User.
class User < ActiveRecord::Base
has_many :comments
end
class Post < ActiveRecord::Base
belongs_to :user
def self.process
Post.all.each do |post|
end
end
end
:
User.find(1).posts.process # See Note 1 below
, 1 2, :
- .
process process_posts. process : User.find(1).orders.process .. User.find(1).process_orders ( 1).
1:
, , . . TL; DR - , User.find(1).posts CollectionProxy, (Post) . scope_attributes, user_id , posts.process. . . 2 .
2:
, , , Post.all.each , , .
, User.find(99).posts.process, Post.all :
SELECT "notes".* FROM "posts" WHERE "posts"."user_id" = $1 [["user_id", 99]]
ID : 99.
@Jesuspc , Post.all.each all.each. , .
,