如何在rails中实现对象组合?

时间:2016-05-12 16:42:25

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

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

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

如何创建此复合模型?

1 个答案:

答案 0 :(得分:0)

在rails中,您可能希望实现所谓的" Form"模型。作为铁杆的新手,这将向您介绍许多奇怪的半高级'主题,但以下是您想要做的。我建议你查看你看不到的任何方法/模块,因为这里有一些魔术轨道使用(验证回调等):

首先根据您提供的属性选择一个班级名称我将致电公司。

    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

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