Question

I want to store url's but extract the base url and store it in different table of its own.

url: example.com/this-is-worth-saving
base url: example.com

URL table:

+----+-----+-------------+
| id | url | base_url_id |
+----+-----+-------------+

Base_url table:

+----+----------+
| id | base_url |
+----+----------+

Should I use the before_create callback in rails to check to see if the base_url already exist in the base_url table and
if it does then grab the id and place it in the url's tables base_url_id
else create the new record the grab the id.

OR

Is there a better solution or schema design perhaps.

I've heard many arguments against the use of callback filters in rails ( 4 ).

Basically I want the base_url_id.

Was it helpful?

Solution

Callbacks are a giant debate in the Rails world. I like them, but I also use them only when absolutely necessary. In this case, I don't think you need callbacks.

I'd recommend using find_or_create_by! on your "base_url" table... Assuming your table is called BaseUrl, you could do:

@base_url = BaseUrl.find_or_create_by!(:base_url => params[:base_url])

Again, this assumes the name of your table is BaseUrl and you're using incoming params which contain a key of base_url. You'd want to modify the above code to fit your needs, but I think find_or_create_by! is what you want, as this will either:

a. Return an existing record with that base_url, or b. Create a new record with that base_url.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top