They are two users:
-
User – logged in user
-
Guest – not logged in visitor.
User and guest can post a question. To post a question, guest must specify his email.
They are two views “new.html.erb” and “new_for_guest.html.erb”. The first one relies to @user variable. The second one does’t.
When question, being created by guest, fails validation, “new_for_guest.html.erb” should be rendered, preserving all the entered data.
The code is following:
def new
@question = Question.new
guest = session[user_id].nil?
respond_to do |format|
if guest
format.html { render "new_for_guest" }
else
format.html { render "new" }
end
end
end
def create
@question = Question.new(params[:question])
guest = session[user_id].nil?
respond_to do |format|
if @question.save
flash[:notice] = 'Question was successfully created.'
format.html { redirect_to(@question) }
else
if guest
format.html { render :action => "new_for_guest" } # problem
else
format.html { render :action => "new" }
end
end
end
When validation fails for guest and “new_for_guest” view is rendered, i see in browser the url “/questions”, instead of “/questions/new”. Because of this, all the stylesheets, used for “new” action are gone.
When validation fails for user and “new” view is rendered, i see the correct url “/questions/new” and everything is ok.
When i just say
format.html{ redirect_to new_question }
“new” action will be rendered, but all the data, user has entered, is gone.
I need to render “new_for_guest” view in “questions/new” context.
How to do it ?
Update
I noticed the same behaviour of untouched code, generated by scaffold.
When by creation, validation is failed, new action is rendered again, but in URL, “/questions” is presented instead of “/questions/new”.
This is strange. Is this a correct behaviour ?
I’ve found similar unanswered question Rails create action is redirecting to index when it should be rendering the new action
This is the correct behavior. As per RESTful routes, when a form is POSTed for an object it is sent to the
/objectURI, implying the creation of a new object with an unknown ID. This is described in the Rails Guides. As a result when validation fails and you simply render the new action, you are on that URI rather than the/object/newURI.Further, you shouldn’t have your styles be specific per action, as there will certainly be unneeded code redundancy there (and I’m not even sure how you’re doing this such that it doesn’t work when the URI changes). The same goes with having multiple views for an action, it is rarely absolutely necessary, and it doesn’t appear it is in your case since you can simply utilize an empty
@userobject when it’s a guest.