简体   繁体   中英

Ruby on Rails - Model Design

I have a model called Note where a user can make notes about different subjects:

rails g scaffold Note sub1:text sub2:text sub3:text ... user:references

A User model has_one :note , and a Note model belongs_to :user

Is this correct, and if not, what is the best way of doing this?

Edit:

Lets say as suggested in the answer below i will make the User model has_many notes and the Note model will only have two attribute content:text and subName:string and then using scopes i can get the notes that belongs to specefic subject, is that a good way ?

It depends on your use case. Yes, this code will run, but I am getting the idea from your description that a User is supposed to be able to have more than just one note . If this is the case, you actually want to use the has_many :note association inside of your User model.

Also, it is generally a bad practice to use numbered columns as a way to allow for multiple values for a record. Instead, you may want to create a Subject model and set up a has_and_belongs_to_many association between it and Note documentation .


Edit to respond to OP edit: Yes, you can do that. Now you are losing the ability to have multiple subjects for a single note, however. But if you are okay with only a single subject for each note, then what you have would work and is simpler than creating a whole new model.

Do be aware, however, that there are downsides to this. If you want to search for all posts with "apples" as the subject, you won't get any posts where a user has put "Apples" (capitalized "A") as the subject, or " Apples" (preceding space) or "Apples " (tailing space), etc. You could overcome this with before_save hooks that normalize the subject text, but what about misspellings or redundant subject s that have semantically identical meaning? Those aren't easy to fix with even using a model, either, but it would be considerably easier , especially if you constrain the user's choices to existing subjects.

You also will be asking the database to use string evaluation as your predicate, which may or may not have performance drawbacks relative to performing a join on a constrained Subject table if the data set gets large enough.

And lastly, either way, if you are going to be using that column to search for specific Note records, you should create an index for it.

I think it's a fine way to do it if you only have a few subject types.

Rails now supports enums, so you could look into that for the subject field.

Depending on how many notes you end up having, you may want to look at adding an index on the subject field.

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