简体   繁体   English

Rails创建带有子属性的模型

[英]rails create model with sub attributes

I am new to rails and building an app to fetch json data from an external website and save it in the database. 我是Rails的新手,正在构建一个应用程序以从外部网站获取json数据并将其保存在数据库中。 The json has the following fields under User: json在用户下具有以下字段:

{ "id": , "name": " ", "username": " ", "email": " ", "address": { "street": " ", "suite": " ", "city": " ", "zipcode": " ", } "phone": " ", "website": " " }, {“ id”:,“ name”:“”,“ username”:“”,“ email”:“”,“ address”:{“ street”:“”,“ suite”:“”,“ city”: “”,“邮政编码”:“”,}“电话”:“”,“网站”:“”},

I know how to create a User model with name, username, and email. 我知道如何使用名称,用户名和电子邮件创建用户模型。 But how do I add address that has multiple sub-attributes. 但是,如何添加具有多个子属性的地址。 I did not see "array" as an option to choose from for creating model. 我没有看到“数组”作为创建模型的选项。 Thank you in advance. 先感谢您。

I think you can try this: 我认为您可以尝试以下方法:

class NameOfYourMigration < ActiveRecord::Migration

  def change
    add_column :your_models, :address, :text
  end

end

class YourModel < ActiveRecord::Base 
 serialize :address, Hash  # if your variable is a Hash
 serialize :address, Array # or for an Array
end

You can do this by associating addresses to a user. 您可以通过将地址与用户关联来实现。

First you should create a new model called user_address for example, with the attributes you desire: 首先,您应该使用所需的属性创建一个名为user_address的新模型:

rails g model user_address address:string number:integer user_id:integer

On your user_address.rb file: 在您的user_address.rb文件上:

belongs_to :user

Then, in your user.rb file you should add 然后,应在user.rb文件中添加

has_many :user_addresses

Once you do this you'll be able to access all the user's addresses by doing the following query: 完成此操作后,您可以通过执行以下查询来访问所有用户的地址:

user.user_addresses

this will give you an 'ActiveRecord::Associations::CollectionProxy' object, where you will be able to iterate: 这将为您提供一个“ ActiveRecord :: Associations :: CollectionProxy”对象,您可以在其中进行迭代:

user.user_addresses.each do |address_instance|
  puts address_instance.address+"#{ address_instance.number}"
end

To manage this in a form, you could follow this guide: https://github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms 要以表格形式进行管理,您可以遵循以下指南: https : //github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM