I'm working on a project with a goal of POSTing a string and returning every third character of that string. The project is built in Ruby/Rails.
I have the (hacky) logic down for getting that third element out, putting it in a new string, and saving this new string it with the new object in the database, but my issue at the moment is that all of this logic is done in the Controller. I'd really like to follow MVC, so my goal is to get all of this logic into the Model.
Currently, the *params
and create
methods in my Controller look like this:
Class TestController < ApplicationController
...
def create
new_output_string = params[:input_string].split("")
final_output_string_array = []
counter = 1
new_output_string.each do |letter|
if counter % 3 == 0
final_output_string_array.append(letter)
end
counter = counter 1
end
final_output_string = final_output_string_array.join("")
@test = Test.create(
input_string: params[:input_string],
output_string: final_output_string
)
render json: @test
end
def test_params
params.require(:test).permit(:input_string, :output_string)
end
So you can see that all of the logic for manipulating this data is in the Controller. I tried writing a method make_output_string
in the model:
Class Test < ApplicationRecord
def self.make_output_string()
new_output_string = params[:input_string].split("")
final_output_string_array = []
counter = 1
new_output_string.each do |letter|
if counter % 3 == 0
final_output_string_array.append(letter)
end
counter = counter 1
end
@final_output_string = final_output_string_array.join("")
end
I hoped that this would manipulate the data before the create
action (I tried using before_create
etc.) calling before_create
, and referencing the method in the controller's create method, but I either get no result or an undefined method
error.
How can I move my logic into the Model so that it can handle the manipulation/creation of the parameters?
CodePudding user response:
You should create a custom setter for input_string on the Model and make it save both input_string and output_string.
Class Test < ApplicationRecord
def input_string=(input_string)
super(input_string)
self.output_string = generate_output(input_string)
end
private
def generate_output(input_string)
new_output_string = input_string.split("")
final_output_string_array = []
counter = 1
new_output_string.each do |letter|
if counter % 3 == 0
final_output_string_array.append(letter)
end
counter = counter 1
end
final_output_string_array.join("")
end
end
Then your controller would be like the following.
Class TestController < ApplicationController
def create
@test = Test.create(input_string: params[:input_string])
render json: @test
end
def test_params
params.require(:test).permit(:input_string, :output_string)
end
end