Skip to content

Commit

Permalink
Cache parent record when calling build on a has_many/one association
Browse files Browse the repository at this point in the history
  • Loading branch information
chewi committed Feb 20, 2017
1 parent be154e7 commit f81ea98
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/her/model/associations/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ def build_association_path(code)
# @private
def build_with_inverse(attributes = {})
@klass.build(attributes.merge(:"#{@parent.singularized_resource_name}_id" => @parent.id)).tap do |resource|
if @opts[:inverse_of]
resource.send "#{@opts[:inverse_of]}=", @parent
elsif @klass.associations[:belongs_to].any? { |a| a[:name].to_s == @parent.singularized_resource_name.to_s }
resource.send "#{@parent.singularized_resource_name}=", @parent
end

begin
resource.request_path
rescue Her::Errors::PathError => e
Expand Down
7 changes: 7 additions & 0 deletions spec/model/associations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ def present?
end
spawn_model "Foo::Comment" do
collection_path "/users/:user_id/comments"
belongs_to :user
has_many :likes
end
spawn_model "Foo::User" do
Expand All @@ -509,6 +510,12 @@ def present?
expect(@comment.user_id).to eq(10)
end

it "caches the parent record" do
@user = Foo::User.new(id: 10)
@comment = @user.comments.build
expect(@comment.user.object_id).to eq @user.object_id
end

it "uses nested path parameters from the parent" do
@like = Foo::User.new(:id => 10).comments.build(:id => 20).likes.build
@like.request_path.should == "/users/10/comments/20/likes"
Expand Down

0 comments on commit f81ea98

Please sign in to comment.