Skip to content

Instantly share code, notes, and snippets.

@mcordell
Last active December 15, 2015 15:29
Show Gist options
  • Save mcordell/5282288 to your computer and use it in GitHub Desktop.
Save mcordell/5282288 to your computer and use it in GitHub Desktop.
Nutrient has_many Recommendation. Recommendation belongs_to Nutrient. Is this the proper way to find and set the nutrient/recommendation relationship as a recommendation is created?
def create
nutrient_id = params[:recommendation][:nutrient_id]
if nutrient_id.blank?
#nutrient_id was blank in the submit, get other recommendation params and re-render 'new'
params[:recommendation].delete(:nutrient_id)
@recommendation=Recommendation.new(params[:recommendation])
render 'new'
else
@nutrient = Nutrient.find(nutrient_id)
if @nutrient
#nutrient was found by id, create recommendation
@recommendation = @nutrient.recommendations.build(params[:recommendation])
if @recommendation.save
redirect_to @recommendation
else
render 'new'
end
else
#nutrient was not found by id, get other recommendation params and re-render 'new'
params[:recommendation].delete(:nutrient_id)
@recommendation = Recommendation.new(params[:recommendation])
render 'new'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment