README.md in arel-helpers-2.1.0 vs README.md in arel-helpers-2.1.1
- old
+ new
@@ -40,16 +40,33 @@
### JoinAssociation Helper
Using pure Arel is one of the only ways to do an outer join with ActiveRecord. For example, let's say we have these two models:
```ruby
+class Author < ActiveRecord::Base
+ has_many :posts
+
+ # attribute id
+ # attribute username
+end
+
class Post < ActiveRecord::Base
+ belongs_to :author
has_many :comments
+
+ # attribute id
+ # attribute author_id
+ # attribute subject
end
class Comment < ActiveRecord::Base
belongs_to :post
+ belongs_to :author
+
+ # attribute id
+ # attribute post_id
+ # attribute author_id
end
```
A join between posts and comments might look like this:
@@ -60,46 +77,46 @@
ActiveRecord introspects the association between posts and comments and automatically chooses the right columns to use in the join conditions.
Things start to get messy however if you want to do an outer join instead of the default inner join. Your query might look like this:
```ruby
-Post
- .joins(
- Post.arel_table.join(Comments.arel_table, Arel::OuterJoin)
- .on(Post[:id].eq(Comments[:post_id]))
- .join_sources
- )
+Post.joins(
+ Post.arel_table.join(Comment.arel_table, Arel::Nodes::OuterJoin)
+ .on(Post[:id].eq(Comment[:post_id]))
+ .join_sources
+)
```
Such verbose. Much code. Very bloat. Wow. We've lost all the awesome association introspection that ActiveRecord would otherwise have given us. Enter `ArelHelpers.join_association`:
```ruby
-Post.joins(ArelHelpers.join_association(Post, :comments, Arel::OuterJoin))
+Post.joins(
+ ArelHelpers.join_association(Post, :comments, Arel::Nodes::OuterJoin)
+)
```
Easy peasy.
`#join_association` also allows you to customize the join conditions via a block:
```ruby
Post.joins(
- ArelHelpers.join_association(Post, :comments, Arel::OuterJoin) do |assoc_name, join_conditions|
+ ArelHelpers.join_association(Post, :comments, Arel::Nodes::OuterJoin) do |assoc_name, join_conditions|
join_conditions.and(Post[:author_id].eq(4))
end
)
```
But wait, there's more! Include the `ArelHelpers::JoinAssociation` concern into your models to have access to the `join_association` method directly from the model's class:
```ruby
include ArelHelpers::JoinAssociation
-Post
- .joins(
- Post.join_association(:comments, Arel::OuterJoin) do |assoc_name, join_conditions|
- join_conditions.and(Post[:author_id].eq(4))
- end
- )
+Post.joins(
+ Post.join_association(:comments, Arel::Nodes::OuterJoin) do |assoc_name, join_conditions|
+ join_conditions.and(Post[:author_id].eq(4))
+ end
+)
```
### Query Builders
ArelHelpers also contains a very simple class that's designed to provide a light framework for constructing queries using the builder pattern. For example, let's write a class that encapsulates generating queries for blog posts: