2012-01-04 21 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

相關問題