My application has two associated models: Magazine and Article:
class Magazine < ActiveRecord::Base
has_one :article
end
class Article < ActiveRecord::Base
belongs_to :magazine
validation_presence_of :title
end
From the Magazine show page I can create a new Article, so my routes.rb is configured like:
resources :magazines, :shallow => true do
resources :articles
end
and in the Magazine show page I have the link “New article”, like:
<%= link_to 'New article', new_magazine_article_path(@article)
and an article helper to pass correct parameters to the form_for:
module ArticlesHelper
def form_for_params
if action_name == 'edit'
[@article]
elsif action_name == 'new'
[@magazine, @article]
end
end
end
so I can use Article form_for like:
<%= simple_form_for(form_for_params) do |f| %> ...
The ArticlesController methods for new and create are:
respond_to :html, :xml, :js
def new
@magazine = Magazine.find(params[:magazine_id])
@article = Article.new
end
def create
@magazine = Magazine.find(params[:magazine_id])
@article = @magazine.build_article(params[:article])
if @article.save
respond_with @magazine # redirect to Magazine show page
else
flash[:notice] = "Warning! Correct the title field."
render :action => :new
end
end
The problem occurs when there is a validation error with the title attribute, and the action new is rendered. In this moment I get the message: undefined method `model_name’ for NilClass:Class in the first line of form_for. I think it is because the @magazine parameter passed in the helper.
How could I solve this problem withou use redirect_to ? (I want to mantain the other attributes that were filled in the form .)
Your
form_for_paramsmethod is returningnil, because theaction_nameis set to ‘create’, not ‘new’ or ‘edit’.Try this: