Rails 4 has_and_belongs_to_many [英] Rails 4 has_and_belongs_to_many

查看:78
本文介绍了Rails 4 has_and_belongs_to_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型.场地和类别.它们相互关联为has_and_belongs_to_many

I have two models. Venues and Categories. They are related to each other as has_and_belongs_to_many

类别已预先填充,并且在表格中我想显示多选内容,以允许在添加场所的同时选择场所的类别.

Categories are pre populated and in the form i want to display a multi-select to allow choosing the categories for a venue while adding a venue.

venue.rb

class Venue < ActiveRecord::Base

  has_and_belongs_to_many :categories

end

category.rb

class Category < ActiveRecord::Base

  has_and_belongs_to_many :venues

end

加入表

create_table "categories_venues", id: false, force: true do |t|
  t.integer "category_id", null: true
  t.integer "venue_id",    null: true
end

add_index :categories_venues, ["category_id", "venue_id"]

大多数在线示例都展示了如何使用其他示例创建模型.我无法弄清楚如何使用多重选择选项,用户可以选择一个或多个类别并自动保存.

Most of the examples online show how to create the models from with another. I am not able to figure out how to have a multi select option where the user can select one or more categories and save it automatically.

我是否需要在控制器中使用builder?并添加accepts_nested_attributes_for?

Do i need to use builder in the controller? and add accepts_nested_attributes_for ?

Rails的新手,也一直尝试搜索和阅读文档.

Am new to Rails and been trying to search and read through the docs as well.

控制器

  def new
    @venue = Venue.new

    @categories = Category.all.order('name ASC')
    @countries = Country.all.order('name ASC').limit(25)
    @regions = Region.all.order('name ASC').limit(25)
    @cities = City.all.order('name ASC').limit(25)

    #render plain: @categories.inspect

  end

查看

  <div class="form-group">
    <%= f.label :parent_id, "Categories:<span class='mandatory'>*</span>".html_safe,:class => 'col-sm-2 control-label' %>
    <div class="col-sm-3">
      <%= f.collection_select(:category_ids, @categories, :id, :name, { :prompt => true }, { :class => 'select-search', :selected => params[:user_id], :data => { :placeholder => 'Please Choose' } }) %>
      <%= show_errors(@venue, :category_ids).html_safe %>
    </div>
  </div>

推荐答案

好吧,问题在于他没有很好地建立关系.我们已通过以下较小的更改对其进行了修复:

Well the problem was that he wasn't creating the relationships well. We've fixed it with this small changes:

def category_ids
  params.permit(category_ids: [])
end

def venue_params
   #removed category_ids from permit
end

def create
   @venue = Venue.new(venue_params)
   if @venue.save
     category_ids.each {|id| @venue.categories << Category.find(id)}
   # rest of the code
end

并进行更新:

def update
   @venue = venue.find(params[:id])
   if @venue.update(venue_params)
      @venue.categories.delete_all
      category_ids.each {|id| @venue.categories << Category.find(id) }

这篇关于Rails 4 has_and_belongs_to_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆