【问题标题】:How to implement object composition in rails?如何在 Rails 中实现对象组合?
【发布时间】:2016-05-12 16:42:25
【问题描述】:

我是 Rails 框架的新手。我正在尝试使用以下复合结构创建一个非 ActiveRecord 支持的模型类 -

{
    "address" : {
        "city" : "Bangalore",
        "state" : "KA"
    },
    "images" : [
        "image-path-1",
        "image-path-2"
        "image-path-3"
    ],
    "facilities" : [
        {
            "name" : "abcd"
        },
        {
            "name" : "xyz"
        }
    ]
}

如何创建这个复合模型?

【问题讨论】:

  • 这是 Ruby 中基本的面向对象编程。我建议查找有关使用 Ruby 编写类的教程,并熟悉面向对象编程的基本概念。

标签: ruby-on-rails ruby rails-activerecord


【解决方案1】:

在 Rails 中,您将寻求实现所谓的“表单”模型。作为 Rails 新手,这将向您介绍许多奇怪的“半高级”主题,但以下是您想要做的。我建议查找任何你没有见过的方法/模块,因为这里有一些在后台使用的魔法轨道(验证回调等):

首先选择一个类名...根据您提供的属性,我将调用类Company。

    class Company

include ActiveModel::Model #This gives you access to the model methods you're used to.
include ActiveModel::Validations::Callbacks #Needed for before_validation

attr_accessor :address
attr_accessor :images
attr_accessor :facilities #This accessor method basically just says you will be using "facilities" as a virtual attribute and it will allow you to define it.

#Add validations here as needed if you're taking these values from form inputs

def initialize(params={}) #This will be executed when you call Company.new in your controller
  self.facilities=params[:facilities]
  #etc for the other fields you want to define just make sure you added them above with attr_accessor or you wont be able to define them.  Attr_accessor is a pure ruby method if it's new to you.
end



  def another_method
   unless self.facilities.somethingYourCheckingForLikeNil?
     errors.add(:facilities, "This failed and what you checked for is not here!"
   end
  end

end

然后在你的控制器中,如果你遵循正常流程,你会得到类似的东西:

def new
  company = Company.new
end

def create
  company = Company.new(company_params)
  #whatever logic here for saving what you may want saved to a database table etc...
end


private

def company_params
   params.require(:company).permit(:facilities, :address, :whatever_other_params_etc)
end

如果没有更多信息,我无法为您提供完整的示例,但这应该可以帮助您了解有关“表单模型”的更多信息。

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多