Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-persisted records try to make HTTP calls for associations with nil foreign_key #343

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/her/model/associations/belongs_to_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def create(attributes = {})
def fetch
foreign_key_value = @parent.attributes[@opts[:foreign_key].to_sym]
data_key_value = @parent.attributes[@opts[:data_key].to_sym]
return @opts[:default].try(:dup) if (@parent.attributes.include?(@name) && @parent.attributes[@name].nil? && @params.empty?) || (@parent.persisted? && foreign_key_value.blank? && data_key_value.blank?)
return @opts[:default].try(:dup) if (@parent.attributes.include?(@name) && @parent.attributes[@name].nil? && @params.empty?) || (foreign_key_value.blank? && data_key_value.blank?)

return @cached_result unless @params.any? || @cached_result.nil?
return @parent.attributes[@name] unless @params.any? || @parent.attributes[@name].blank?
Expand Down
5 changes: 5 additions & 0 deletions spec/model/associations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@

@user_with_included_data = Foo::User.find(1)
@user_without_included_data = Foo::User.find(2)
@user_without_organization_and_not_persisted = Foo::User.new(organization_id: nil, name: "Katlin Fünke")
end

let(:user_with_included_data_after_create) { Foo::User.create }
Expand Down Expand Up @@ -210,6 +211,10 @@
@user_without_included_data.organization.name.should == "Bluth Company"
end

it "returns nil if the foreign key is nil" do
@user_without_organization_and_not_persisted.organization.should be_nil
end

it "fetches belongs_to data even if it was included, only if called with parameters" do
@user_with_included_data.organization.where(:foo_id => 1).name.should == "Bluth Company Foo"
end
Expand Down