Skip to content

Commit

Permalink
Fix change tracking when fetching from an association collection
Browse files Browse the repository at this point in the history
This requires ActiveModel 4.2+.
  • Loading branch information
chewi committed Feb 20, 2017
1 parent 76dc1e5 commit 550663a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/her/model/associations/has_many_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,15 @@ def create(attributes = {})
def fetch
super.tap do |o|
inverse_of = @opts[:inverse_of] || @parent.singularized_resource_name
o.each { |entry| entry.send("#{inverse_of}=", @parent) }

o.each do |entry|
entry.send("#{inverse_of}=", @parent)

# This fix requires ActiveModel 4.2+.
if entry.respond_to?(:clear_attribute_changes, true)
entry.send(:clear_attribute_changes, [inverse_of])
end
end
end
end

Expand Down
12 changes: 11 additions & 1 deletion spec/model/dirty_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Her::API.setup url: "https://api.example.com" do |builder|
user1 = { id: 1, fullname: "Lindsay Fünke" }
user2 = { id: 2, fullname: "Maeby Fünke" }
post1 = { id: 1, user_id: 1, body: "Hello" }

builder.use Her::Middleware::FirstLevelParseJSON
builder.use Faraday::Request::UrlEncoded
Expand All @@ -18,7 +19,8 @@
stub.put("/users/1") { [200, {}, { id: 1, fullname: "Tobias Fünke" }.to_json] }
stub.put("/users/2") { [400, {}, { errors: ["Email cannot be blank"] }.to_json] }
stub.post("/users") { [200, {}, { id: 1, fullname: "Tobias Fünke" }.to_json] }
stub.get("/users/1/posts/1") { [200, {}, { id: 1, user_id: 1, body: "Hello" }.to_json] }
stub.get("/users/1/posts") { [200, {}, [post1].to_json] }
stub.get("/users/1/posts/1") { [200, {}, post1.to_json] }
end
end

Expand Down Expand Up @@ -92,6 +94,14 @@
end
end

context "for an existing resource from an association collection" do
let(:post) { Foo::User.find(1).posts.first }
it "has no changes" do
post.changes.should be_empty
post.should_not be_changed
end
end

context "for resources from a collection" do
let(:users) { Foo::User.all.fetch }
it "has no changes" do
Expand Down

0 comments on commit 550663a

Please sign in to comment.