简体   繁体   中英

What is the best way to structure this model/DB assiociations

I am creating a project, and I want to structure the databases in the best way possible. I have a model called Event, now i would like a single event (think a baseball game) to belong to a month (ie August) and belong to a category (ie baseball) AND belong to a user (ie current_user)

In otherwords, I would like a month, a category, and a user to have many events, but I don't want the events to be duplicated. The same event object would be returned by:

august.events.find_by_id(1)
baseball.events.find_by_id(1)
current_user.events.find_by_id(1)

Any tips? My initial thought is to just set up the relations as I described above.. But I am curious to what is the best approach to creating an event object since:

august.events.new("foo")
baseball.events.new("foo")
current_user.events.new("foo")

would all yield three different event objects, when I am looking to just create one.

Can I do something like this?

Event.new(:category => "baseball", :month => "august")

then what would be the best approach to declaring a user "has that" event, and from there run commands such as baseball.events.all and august.events.all. And how would I dive deeper into the association madness if I wanted say Category -> Sports -> Baseball -> event

Thanks for any help, it is much appreciated.

this isn't an answer, per se. It is mainly to give you an idea of the flexibility of the API.


The schema, from what I can tell, is correct. Event has month and category (or category_id ) and user_id . You can create all manner of helper methods to operate on that model.

For example, with a few scopes:

class Event
  scope :for_month,    ->(m) { where(month: m) }
  scope :for_category, ->(c) { where(category: c) }
  scope :for_user,     ->(u) { where(user: u) }
end

# usage

Event.for_month("august").for_category("baseball").for_user(current_user)

# below, month "august" will be set on instance
current_user.events.for_month("august").new("foo") 

But all of this is pointless. With those relationships in place, you can access the Event from User or Category and fill in the details yourself:

Event.where(month: "august", category: "baseball", user: current_user)
current_user.events.where(month: "august", category: "baseball")

current_user.events.new(month: "august", category: "baseball")

There are a tonne of ways to access and manipulate this data. I'm not sure you can reduce it much further than the above. You could go crazy and add a scope with multiple arguments:

class Event
  scope :for_mcu, ->(m, c, u) {
    for_month(m).for_category(c).for_user(u)
  }
end

# usage

Event.for_mcu("august", "baseball", current_user)

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