A
A
Anton2016-01-26 20:39:21
Ruby on Rails
Anton, 2016-01-26 20:39:21

What is the best way to write to the database?

Hello!
There are news and categories tables. A news item can have several categories. Now, when adding news, I add a link in this way:

if params[:news][:categories]
  params[:news][:categories].each do |category|
    @news.categories_news.create(category_id: category.first.to_i)
  end
end

The list of categories is a checkbox with the name:
news[categories[тут_id_категории]]
There is a feeling that sorting through everything in a loop and stupidly entering each category into a table is not the best solution. Interested in the most correct way to write relationships in the database?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zaporozhchenko Oleg, 2016-01-26
@c3gdlk

you can use accept_nested_attributes - https://robots.thoughtbot.com/accepts-nested-attri...

S
Sworg, 2016-01-27
@Sworg

That's right, not the best solution.
For starters, use strong_params if you're going that route. https://github.com/plataformatec/simple_form will help you to save links correctly . There are many basic examples for various options (checkboxes, radio buttons, etc.).
And also, I advise you to look towards the Form Object pattern (see Google) and try to use it for your case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question