Skip to content

Commit

Permalink
Merge pull request #188 from monterail/belongs-to-nested-models-fix-f…
Browse files Browse the repository at this point in the history
…or-missing-foreign-key

Belongs to nested models fix for missing foreign key
  • Loading branch information
remi committed Nov 3, 2013
2 parents 7efacf1 + d59b19e commit 79dc336
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/her/model/associations/belongs_to_association.rb
Expand Up @@ -72,7 +72,8 @@ def create(attributes = {})
# @private
def fetch
foreign_key_value = @parent.attributes[@opts[:foreign_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 = @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?)

if @parent.attributes[@name].blank? || @params.any?
path_params = @parent.attributes.merge(@params.merge(@klass.primary_key => foreign_key_value))
Expand Down
6 changes: 6 additions & 0 deletions spec/model/associations_spec.rb
Expand Up @@ -249,6 +249,7 @@
builder.use Faraday::Request::UrlEncoded
builder.adapter :test do |stub|
stub.get("/users/1") { |env| [200, {}, { :id => 1, :name => "Tobias Fünke", :organization => { :id => 1, :name => "Bluth Company Inc." }, :organization_id => 1 }.to_json] }
stub.get("/users/4") { |env| [200, {}, { :id => 1, :name => "Tobias Fünke", :organization => { :id => 1, :name => "Bluth Company Inc." } }.to_json] }
stub.get("/users/2") { |env| [200, {}, { :id => 2, :name => "Lindsay Fünke", :organization_id => 1 }.to_json] }
stub.get("/users/3") { |env| [200, {}, { :id => 2, :name => "Lindsay Fünke", :company => nil }.to_json] }
stub.get("/companies/1") { |env| [200, {}, { :id => 1, :name => "Bluth Company" }.to_json] }
Expand All @@ -264,6 +265,7 @@
@user_with_included_data = Foo::User.find(1)
@user_without_included_data = Foo::User.find(2)
@user_with_included_nil_data = Foo::User.find(3)
@user_with_included_data_but_no_fk = Foo::User.find(4)
end

it "maps an array of included data through belongs_to" do
Expand All @@ -281,6 +283,10 @@
@user_without_included_data.company.id.should == 1
@user_without_included_data.company.name.should == "Bluth Company"
end

it "does not require foreugn key to have nested object" do
@user_with_included_data_but_no_fk.company.name.should == "Bluth Company Inc."
end
end

context "building and creating association data" do
Expand Down

0 comments on commit 79dc336

Please sign in to comment.