【问题标题】:Using single model for multiple tables对多个表使用单个模型
【发布时间】:2012-04-23 21:05:16
【问题描述】:

我想知道是否可以组合来自不同表的列并将其用作 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),但看起来我无法使用这种方法拆分多个表中的列。

【问题讨论】:

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


    【解决方案1】:

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

    向职位添加帖子

    job[posts_attributes] = [{ :title =&gt; "test", :description =&gt; "Lorem ipsum"}]

    从工作中删除帖子

    job[posts_attributes = [{ :id:20, :_destroy =&gt; true}]

    希望对你有所帮助;)

    【讨论】:

    • 感谢 Tronix117。这正是我所期待的。
    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多