0

I'm having issues getting an instance variable to show up in my views. I'm setting it using a private method, and I'm using a before_filter to ensure that I can access it in the two places I need it. However, the instance variable is not showing up in the view, let alone having the needed action.

In my controller I have

class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_filter :set_form, :only => [ :edit_password, :edit_email ]
...
def edit_password 
@user = current_user
  set_form('password') 
end 
def edit_email
  @user = current_user
  set_form('email')
end
...
private
def set_form(edit_type)
  @form = edit_type
end 

Here is the view file

<h1>Edit Your Account</h1>

<title><%= @form %></title>
<% if @form == 'email' %>
<%= render 'edit_email_form' %>
<% else %> 
<%= render 'edit_password_form' %>
<% end %>
<%= link_to 'Back', user_path(@user) %>

I'm not sure what else I need to do to be able to use the instance variable in the view. I'm also wondering whether it's still possible to access the instance variable in the update statement after? Any help would be appreciated!

1 Answer 1

1

There's no value in setting set_form in a before_filter, as you're calling it in your methods.

You need to explicitly render your view file... I don't see you're doing that. If the form is called (for example) edit_value.html.erb then your two edit_... methods need to have

render :edit_value

Instance values are not available in the update statement. When you update nothing is available except the information submitted in your form or url, or anything you saved in the session hash, or anything you persisted to your database.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! Is it ok do that kind of thing in a view? or is that not supposed to be allowed in the rails MVC framework?
It's allowed, but generally you want to minimize logic in a view as much as possible. If I were writing this, I would have edit_password and edit_email render separate views. If there's any stuff that should be in common between the two (like your link_to :back) I would put that in a partial that's called by both forms..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.