karnesJ.R
karnesJ.R

Reputation: 326

Ruby on Rails Model Actions

I am working on a webserver project and have little experience with MVC architecture. What reading I have done points me to the idea of "Skinny Controllers, Fat Models." Keeping this in mind, I've tried tinkering around in rails to get the effect I'm looking for:

I accept through a form a string and must sanitize it (Assuming this is done through Callbacks). After it has been sanitized, I'm converting it into an array and sorting it.

Each step of the sort is being recorded in a variable @states. I need to put @states variable into the database when the process is done.

My question is: how is this setup best enacted? I think I'm correct that the sanitation should be performed through a callback... but the second part is what's giving me fits.

Here's something of an example:

recieve input: "4 3 2 1\r\n5 2 2 1\r\n1 5 4 3"
sanitize input to: 4 3 2 1 5 2 2 1 1 5 4 3 # Presumably through a callback
until input.sorted? do:
    input.bubblesort(@states) # each time bubblesort moves an entry, it sends a copy of the array to @states
#Do something with @states in the model.rb file

I would love some input on this because I'm at an impasse and nothing quite makes sense.

Upvotes: 0

Views: 91

Answers (1)

bkunzi01
bkunzi01

Reputation: 4561

The value you get from the form submission will be stored in the params hash. I'm fairly certain rails sanitizes everything automatically as of rails 4 and that you only need to be wary of tainted data during ActiveRecord queries.

Assuming you have your input: "4 3 2 1\r\n5 2 2 1" I would replace all r's and n's with spaces via the .gsub method. Once you have input such as input= "4 3 2 1 5 2 2 1" you can do input.split(/\s/) which will convert the string to an array with all elements split where there are spaces. From there you can easily order the array since strings are comparable in ruby.

EDIT***

@states = input.bubblesort(@states) #then maybe something like this depending on your table setup: @new_state = YourModel.create(@states) ' If you're using a db like Postgresql you can specify that the input of a certain attribute will be an array. This is done as so via a migration: 'add_column :table_name, :column_name, :string, array: true, default: []'

Normally, the only logic that is kept in the model are your validations and sort/scope methods.

Upvotes: 1

Related Questions