2012-01-04 20 views
0

我是Ruby on Rails(和StackoverFlow作为注册会员)的新手 虽然,我知道我可以将Strings与myString.split(",")分开。 那不是问题。Ruby on Rails窗体:我如何拆分一个字符串并将其保存为一个数组?

我有什么:

嵌套表单字段的另一种形式的动态数量,这工作好,到目前为止

我想要做什么:

我有一个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 
+0

可能是你可以尝试归列“climbing_routes”。这可以让你有一个可能关系或您可以尝试系列化 – PriteshJ 2012-01-04 19:18:33

回答

0

一件事,然后覆盖默认吸气的轨道模型给出你:

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

或者,如果你不打算总是想要数组,而宁愿保留默认的吸气剂圆通,你可以创建一个单独的方法,并调用它,当你需要它

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

希望这有助于!

0

在您的数据库模式中,将climbing_routes从'string'更改为'text'。

在sector.rb ...

serialize :climbing_routes 

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

在数据库中,climbing_routes将存储为YAML,当你访问它,它会出来一个数组。

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

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

+0

谢谢,我gonny试试! – Stefan 2012-01-05 08:32:33

相关问题