I want to make a Keywords table that stores words in a string (from a phrase with spaces) and if the user enters a phrase it adds a reference to the keyword id in a phrases table.
I think the tables should look like this:
Keyword:
ID | Word
-----------
1, a
2, keyword
3, phrase
Domain:
ID | Name
-----------
1, findme.org
Phrase:
Phrase_ID | Keyword_ID | Domain_ID | Word_Weight
-----------
1, 1, 1, 0
1, 2, 1, 1
1, 3, 1, 2
Is there a way that I can do this in rails possibly with a has_many relationship so that I could get a phrase by passing @domain.phrases returning a list of all of the phrases with the same Domain_ID, and @keyword.phrases lists all of the phrases that contain a keyword with Keyword_ID
My goal is to avoid duplicate rows in any of the tables, is this convoluted? Could you suggest a better design that is the rails way of doing things?
What your describing is very similar to the concept of tags, and so you can use any of the tagging libraries already available, and/or study their structure for a solid solution.
For example, here is the migration for the
acts_as_taggable_ongem, which will give you an idea of how other people have done this, including the models (and relationships between models) in the code.These tools provide, with very little code, the ability to add
@domain.tagsto any record. Some of the libraries also let you define what you want to call the tags – so if you want to call them keywords, you can do that, and have calls like@domain.keywordsor@domain.phrases, etc., like in your example.Also, if the ultimate goal of this is to add keywords in order to aid in searching, there are great search libraries and tools that enable full text search (where text, titles, etc. are automatically indexed for keywords) without needing to explicitly define keywords.
Really depends on where you want to go, but those are a couple of directions for you.