简体   繁体   中英

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

I'm new to ruby on rails (and StackoverFlow as a registered member) Though, I know I can split Strings with myString.split(",") eg Thats not the Problem.

What I have:

A dynamic number of nested form fields in another form, which works okay so far

What I wanna do:

I have a Textarea in each Nested-Form. The User should type in several words, seperated by "," These words should be saved as an Array, so I can call them via @sector.climbing_routes (as an Array) later.

Right now "climbing_routes" is just a very long String.

How can I handle this Problem?

Here's some code:

_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>

Schema Sectors:

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

One thing you could do is simply store them as a comma separated list, then overwrite the default getter that the rails model gives you:

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

Or, if you aren't going to ALWAYS want the array, and would rather leave the default getter in tact, you could create a separate method and call it when you need it

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

Hope this helps!

In your database schema, change climbing_routes from 'string' to 'text'.

Within sector.rb ...

serialize :climbing_routes

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

In the database, climbing_routes will be stored as YAML, and when you access it, it'll come out as an array.

Since you're handling user input, I used / *, */ to split the climbing_routes data, so that any extra spaces around the comma are ignored.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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