简体   繁体   中英

Rails 3 associations issue: bands have codes, users have codes but users don't have bands… How should I modify

I have Users, Bands and Codes

Bands have many Codes, Users have many codes, but Users and Bands don't have any relationship.

Bands have many codes because users create codes that are related to a band. There may be many bands for which a user has codes for...

I guess a user could have a band but I do not want my urls to be users/:id/bands/:id/codes/:id

Ideas?

EDIT: I just noticed that your question says you do not want that url. My answer is the reverse, sorry.

If that's what want your url to be, then you should definitely make Users have many Bands, and Bands have many Codes. Then use a has_many :though to make Users have many Codes. Like this:

class Code < ActiveRecord::Base
  belongs_to :band
  belongs_to :user, :through => :band
end

class Band < ActiveRecord::Base
  has_many :codes
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :bands
  has_many :codes, :through => :bands
end

Then set up your routes using nested resources:

map.resources :users do |users|
  users.resources :bands do |bands|
    bands.resources :codes
    end
  end
end

That would make code_path(1, 2, 3) map to /users/1/bands/2/codes/3 . And your CodesController#show action would have access to user_id (1), band_id (2), and id (3).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM