繁体   English   中英

Ruby on Rails表单:如何拆分字符串并将其另存为数组?

[英]Ruby on Rails Form: How can I split a String and save it as an Array?

我是Ruby的新手(并且是注册会员的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

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

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

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

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

希望这可以帮助!

在您的数据库模式中,将climbing_routes从“字符串”更改为“文本”。

在ector.rb中...

serialize :climbing_routes

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

在数据库中,climbing_routes将存储为YAML,当您访问它时,它将作为数组出现。

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

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

暂无
暂无

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

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