将单个模型用于多个表

时间:2012-04-23 21:05:16

标签: ruby-on-rails design-patterns single-table-inheritance sti

我想知道是否可以组合来自不同表的列并将其用作Rails中的一个模型。我下面有两个表,一个包含通用列和其他专门列。

posts
--------------
id
title
description
created_at
updated_at

jobs
--------------
post_id
category_id
job_type
duration
salary

在Rails模型中,

class Job < ActiveRecord::Base
#
end

在保存作业模型时,应该在各个表中保存列。我想过使用单表继承(STI),但看起来我不能用这种方法在多个表中拆分列。

1 个答案:

答案 0 :(得分:1)

您好,您只需要使用accepts_nested_attributes_for,然后您可以使用post密钥在保存jobs时填写posts_attributes列。

将帖子添加到作业

job[posts_attributes] = [{ :title => "test", :description => "Lorem ipsum"}]

删除作业中的帖子

job[posts_attributes = [{ :id:20, :_destroy => true}]

希望能帮到你;)