简体   繁体   English

Rails:设计具有未知属性的模型

[英]Rails: designing a model with unknown attributes

In my app I have a model called Address . 在我的应用程序中,我有一个称为Address的模型。 The address field therein is the only required field, but the model can have any number of different other attributes. 其中的address字段是唯一需要的字段,但是模型可以具有任意数量的其他不同属性。

Addresses will be created by importing rows from a .csv file. 地址将通过从.csv文件导入行来创建。 The CSV has to have an address column but may have many others, and they can be anything else and therefore impossible to predict. CSV 必须有一个address栏,但可能还有许多其他栏,它们可以是其他任何东西,因此无法预测。

How can I store this information accurately without having to add new DB columns each time? 如何准确地存储此信息,而不必每次都添加新的数据库列? Can I make something like an extra DB column that stores information from columns not in the model? 我可以做一些extra DB列之类的事情来存储模型中不在列中的信息吗? Can I run queries on that field (albeit bastardized)? 我可以在该字段上运行查询吗(尽管已混为一谈)? Finally, when exporting this information back into CSV can I export that extra information back out? 最后, 这些信息导出回CSV时,我可以将这些extra信息导出吗?

One way to solve this is to use Postgres as a database and have a table with 2 columns: address and data where data is of jsonb type. 解决此问题的一种方法是将Postgres用作数据库,并具有一个包含两列的表: addressdata ,其中数据为jsonb类型。 What that gives you is an ability to push arbitrary key/value data. 这给您带来了推送任意键/值数据的能力。 You still can query it via SQL and have indexes on those fields. 您仍然可以通过SQL查询它,并在这些字段上具有索引。

Alternative would be to use a NoSQL database like Mongo or Couch. 替代方法是使用NoSQL数据库,例如Mongo或Couch。

You can store your data as JSON in any text type column.. and retrieve it like 您可以在任何text类型列中将数据存储为JSON

<% @applicant_user_workflow_step.properties.each do |key, value| %>
      <tr>
        <td><strong><%= key %> </strong></td>
      </tr>
      <tr>
        <td><%= value %></td>
      </tr>
 <% end %>

or 要么

<%= fields_for :properties, OpenStruct.new(@applicant_user_workflow_step.properties) do |builder| %>
      <% @workflow_step.fields.order(:order_value).each do |field| %>
        <div class="row">
          <% if field.field_type.eql?('rating') %>
            <%= render "applicants/fields/application_custom_rating/rating", field: field, f: builder %>
          <% else %>
            <%= render "applicants/fields/#{field.field_type}", field: field, f: builder %>
          <% end %>
        </div>
      <% end %>
    <% end %>

Openstruct allows you to access key as instance methods for a hash Openstruct允许您将key作为hash instance方法进行访问

or simplly follow this 或简单地遵循此
blog: http://railscasts.com/episodes/403-dynamic-forms?view=asciicast 博客: http//railscasts.com/episodes/403-dynamic-forms? view = asciicast
answer: Using Rails serialize to save hash to database 答案: 使用Rails序列化将哈希保存到数据库

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

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