Reputation: 8397
I'm trying to incorporate validation into some of my models, but when doing that, if something doesn't validate, I get the error messages "You have a nil object when you didn't expect it!", "You might have expected an instance of Array." and "The error occurred while evaluating nil.map". Taking a look at my code, I add in the lines "validates_uniqueness_of :name" and "validates_format_of :name, :with => /^[A-Za-z\d_]+$/" right after line 3, and whenever I make a submission that would not validate, I get the errors.
Application trace:
app/views/subreddits/new.html.haml:13:in `block in _app_views_subreddits_new_html_haml___455774545377436650_34289940'
app/views/subreddits/new.html.haml:4:in `_app_views_subreddits_new_html_haml___455774545377436650_34289940'
app/controllers/subreddits_controller.rb:53:in `block (2 levels) in create'
app/controllers/subreddits_controller.rb:48:in `create
'
Upvotes: 0
Views: 185
Reputation: 36944
Basically, on the create
action of the controller, you need to set @link_types
so that when you fail to save, you can render the new
template properly. You probably should set the @link_types
value as a constant or do it in a helper to make it DRYer.
def create
params[:subreddit][:created_by_id] = session[:user_id]
@subreddit = Subreddit.new(params[:subreddit])
respond_to do |format|
if @subreddit.save
format.html { redirect_to @subreddit, notice: 'Subreddit was successfully created.' }
format.json { render json: @subreddit, status: :created, location: @subreddit }
else
format.html do
@link_types = {"link" => "link", "text" => "text", "both" => "both"}
render action: "new"
end
format.json { render json: @subreddit.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 3