简体   繁体   English

在 Rails 上的 Ruby 中只有一个 model 时向多个表添加记录?

[英]Adding records to multiple tables when only have one model in Ruby on Rails?

I have three models clients , client_categories and clients_category_merge .我有三个模型clientsclient_categoriesclients_category_merge I want to store clients_id and client_categories_id into clients_category_merge table, as a single client can have multiple client categories.我想将clients_idclient_categories_id存储到clients_category_merge表中,因为单个客户端可以有多个客户端类别。

How do I add the record to 2 tables ( clients and clients_category_merge ) when I only have one model ( clients ) when submitting the form?当我在提交表单时只有一个 model ( clients )时,如何将记录添加到 2 个表( clientsclients_category_merge )?

I am sure there is a good way of doing this.我相信有一个很好的方法可以做到这一点。 But I am pretty new to Rails and lost on this one.但是我对 Rails 还很陌生,并且迷失了这一点。

The has_many:through association will add the proper records for you. has_many:through关联将为您添加适当的记录。

class Client < ActiveRecord::Base
  has_many :client_categories_merges
  has_many :client_categories, :through => :clients_categories_merges
end

class ClientCategories < ActiveRecord::Base
  has_many :client_categories_merges
  has_many :clients, :through => :clients_categories_merges
end

class ClientCategoryMerges < ActiveRecord::Base
  belongs_to :client_category
  belongs_to :client
end

Check out this guide 查看本指南

Edit : And this one for the corresponding forms编辑:而这个对应的 forms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM