I need criticisms and refactoring advice for my controller code:
class ItemsController < ApplicationController
def new
end
def create
params = items_params
if not titles_and_urls_are_same_length(params)
render :new
end
collection = false
if params[:titles].length > 1
collection = true
end
element = nil
if collection
collection = RecommendedCollection.new
params[:titles].each_with_index do |title, index|
resource = RecommendedResource.new(title: title, url: params[:urls][index])
collection.resources << resource
end
if not collection.save
return render :new
end
else
resource = RecommendedResource.new(title: params[:titles][0], url: params[:urls][0])
if not resource.save
return render :new
end
end
if not RecommendedItem.create(element: element)
return render :new
end
render :new
end
private
def titles_and_urls_are_same_length(params)
params[:titles].length == params[:urls].length
end
def items_params
params.permit(:description, titles: [], urls: [])
end
end
Parameter example:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"......", "titles"=>["Learning to program in ruby", "Refactoring Code blog"], "urls"=>["http://www.hi.com", "http://www.ruby-master.com"], "description"=>"Improve your ruby skills", "commit"=>"Recommend"}
The idea behind the controller is that the user submits a link along with a URL and description to a site they like. If you submit a single link, then it is just a RecommendedResource
, if you submit multiple links then it is to be turned into a "collection" or RecommendedCollection
. That is why I check for the length of the params (which is probably not a good way to write the code).
They all go into a RecommendedItem
to show in the feed, so I loop through one model only.
Here is an image that explains the visual results: