【问题标题】:Ruby on Rails Form: How can I split a String and save it as an Array?Ruby on Rails 表单:如何拆分字符串并将其保存为数组?
【发布时间】:2012-02-02 15:53:05
【问题描述】:

我是 ruby​​ on rails 的新手(并且 StackoverFlow 作为注册会员) 不过,我知道我可以使用 myString.split(",") 拆分字符串,例如 那不是问题。

我有什么:

另一个表单中的动态数量的嵌套表单字段,目前还可以

我想做的事:

我在每个嵌套表单中都有一个 Textarea。 用户应输入多个单词,以"," 分隔 这些单词应该保存为Array,,以便我以后可以通过@sector.climbing_routes(作为数组)调用它们。

现在“climbing_routes”只是一个很长的字符串。

我该如何处理这个问题?

这里有一些代码:

_sector_fields.html.erb (Nested Fields):

    <div class="sector">
    Sektor:
    <table>
        <tr>
            <th><%= f.label :name %></th><th><%= f.label :description %></th><th><%= f.label :climbing_routes %></th>
        </tr>
        <tr>
            <th><%= f.text_field :name %></th>
            <th rowspan="5"><%= f.text_area :description, :rows => 5 %></th>
            <th rowspan="5" ><%= f.text_area :climbing_routes , :rows => 6%></th>
        </tr>
        <tr>
            <th>Bild 1</th>
        </tr>
        <tr>
            <th><%= f.file_field :topo %></th>
        </tr>
        <tr>
            <th>Bild 2</th>
        </tr>
        <tr>
            <th><%= f.file_field :topo2 %></th>
        </tr>
    </table>
</div>

架构扇区:

create_table "sectors", :force => true do |t|
t.string   "name"
t.string   "topo"
t.string   "topo2"
t.string   "description"
t.integer  "climbing_area_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "climbing_routes"
end

【问题讨论】:

  • 也许你可以尝试规范化列“climbing_routes”。这可以让你有一个可能的关系,或者你可以尝试序列化

标签: html ruby-on-rails ruby forms nested-forms


【解决方案1】:

您可以做的一件事是将它们存储为逗号分隔的列表,然后覆盖 rails 模型为您提供的默认 getter:

def climbing_routes
  read_attribute(:climbing_routes).split(",")
end

或者,如果您不总是想要该数组,而宁愿保留默认的 getter,您可以创建一个单独的方法并在需要时调用它

def climbing_routes_array
  self.climbing_routes.split(",")
end

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在您的数据库架构中,将 crawl_routes 从“字符串”更改为“文本”。

    在扇区.rb 内 ...

    serialize :climbing_routes
    
    def climbing_routes=( x )
        write_attribute( :climbing_routes, x.split(/ *, */) )
    end
    

    在数据库中,climbing_routes 会存储为 YAML,当你访问它时,它会以数组的形式出现。

    由于您正在处理用户输入,因此我使用 /*、*/ 来拆分登山路线数据,以便忽略逗号周围的任何多余空格。

    http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 2010-11-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      相关资源
      最近更新 更多