Answer the question
In order to leave comments, you need to log in
RoR 4 How to save extra options with has_many and form.select?
There are models:
# Посты
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, :through => :post_categories
end
# Категории
class Category < ActiveRecord::Base
has_many :post_categories
has_many :posts, :through => :post_categories
end
# Поля таблицы
# post_id,
# category_id,
# lang - string(2) например "en" или "ru"
class PostCategory < ActiveRecord::Base
has_one :post
has_one :category
end
<div class="col-sm-5">
<%= f.select :category_ids, options_for_select(Category.all.collect { |c| [c.title, c.id] },@post.categories.collect { |c| c.id }), {:include_hidden => false}, {:multiple => true, :class => 'form-select form-control-static', :style => 'width: 100%'} %>
</div>
# Сохранение нового поста
def create
@post = Post.new(post_params)
# ^^^
# При создании поста я знаю, как передать 3 параметр в таблицу связей, потому что
# уже имею все данные в связях
@post.post_categories.each do |с|
с.lang = 'ru'
end
if @post.save
redirect_to post_path(@post)
else
render 'new'
end
end
def update
@post = Post.find(params[:id])
# Как передавать параметры lang сюда, при обновлении категорий у поста?
if @post.update(post_params)
redirect_to post_path(@post)
else
render 'edit'
end
end
private
def post_params
params.require(:post).permit(:title, {:category_ids => []})
end
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question