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

primary_key unsettable with has_many #60

Closed
jgillman opened this issue Jun 4, 2013 · 4 comments
Closed

primary_key unsettable with has_many #60

jgillman opened this issue Jun 4, 2013 · 4 comments

Comments

@jgillman
Copy link

jgillman commented Jun 4, 2013

foreign_key works just fine, but primary_key always uses id.

Given the following:

# app/models/state.rb
class State < ActiveHash::Base
  include ActiveHash::Associations
  has_many :cities, primary_key: 'abbrev', foreign_key: 'state'

  self.data = [
    { id: 1, name: "California", abbrev: "CA" }
  ]
end

# app/models/city.rb
class City < ActiveRecord::Base
  ... # city.state would be "CA"
end

The following will fail because it looks for the value id and not abbrev

s = State.find_by_name "California"
s.cities

The above would run something like:

SELECT "cities".* FROM "cities"  WHERE "cities"."state" = 1

When it should run:

SELECT "cities".* FROM "cities"  WHERE "cities"."state" = "CA"

I believe it should be fairly easy to add it to lib/associations/associations.rb but I'm pretty green and unsure of all the implications.

@zilkey
Copy link
Collaborator

zilkey commented Jun 17, 2013

This seems like an intuitive patch. Before I think about how it might be implemented, could you just use the abbreviation as the id? That is, do you store the id anywhere in the db?

ActiveHash should work fine with string ids (see https://github.com/zilkey/active_hash/blob/master/spec/active_hash/base_spec.rb#L366)

Would that suit your current situation?

@tomtaylor
Copy link
Contributor

This'd be great. We're migrating a bunch of databased based models to use ActiveHash, and this would help us simplify the transition.

@zilkey
Copy link
Collaborator

zilkey commented Oct 2, 2013

Released in v1.2.0

@zilkey zilkey closed this as completed Oct 2, 2013
@jgillman
Copy link
Author

jgillman commented Oct 2, 2013

Woo! Thanks @tomtaylor 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants