【问题标题】:How to refer to namespaced model from related model?如何从相关模型中引用命名空间模型?
【发布时间】:2017-02-16 03:41:28
【问题描述】:

我想在“dessert”下命名一些“fruit”模型,所以我创建了一个名为“dessert”的模型子目录,并在其中放置了一个“fruit”模型。

app/models/dessert/fruit.rb

class Dessert::Fruit < ActiveRecord::Base
    def self.table_name_prefix
        'dessert_'
    end
end

附表名为:dessert_fruits,我可以进入rails控制台并成功执行Dessert::Fruit.all

现在我想使用has_oneaccepts_nested_attributes_for 创建与另一个模型(meal.rb)的关联,但我不知道如何引用命名空间模型(下面的xxxxx):

app/models/meal.rb

class Meal < ActiveRecord::Base
    has_one :xxxxx, dependent: :destroy, autosave: true
    accepts_nested_attributes_for :xxxxx
    # replacing :xxxxx with :dessert_fruit does not work
end

【问题讨论】:

    标签: ruby-on-rails model-associations


    【解决方案1】:

    尝试显式添加类名:

    class Meal < ActiveRecord::Base
        has_one :fruit, dependent: :destroy, autosave: true, class_name: '::Dessert::Fruit'
        accepts_nested_attributes_for :fruit
    end
    

    This article 对模块组织进行了更深入的讨论。

    【讨论】:

    • 非常感谢。你的回答让我可以继续我的工作。我很感激!
    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2018-11-09
    • 2013-05-28
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多