开发者

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

开发者 https://www.devze.com 2023-03-16 14:19 出处:网络
I have three models clients, client_categories and clients_category_merge. I want to store clients_id and client_categories_id into clients_开发者_如何学Pythoncategory_merge table, as a single client

I have three models clients, client_categories and clients_category_merge. I want to store clients_id and client_categories_id into clients_开发者_如何学Pythoncategory_merge table, as a single client can have multiple client categories.

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?

I am sure there is a good way of doing this. But I am pretty new to Rails and lost on this one.


The has_many :through association will add the proper records for you.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消