Pindub_Amateur
Pindub_Amateur

Reputation: 328

Rails passing parameters between controller methods

So I have 2 pages : Welcome & Details.

In the Welcome page, I'm asking the user to input their name and click on a button which takes you to details page. Creates an entry in db with the given name.

In the Details page, I'm asking for the age and gender. These details I'm updating in db against the name entered in the previous page.

Now, these are my two methods.

 def welcome
     @name = params[:name]
     if @fname
       then @record= Names.create({:name => @name})
     end
 end

 def details
     @human=Names.last
     @human.update_attributes({:age=> params[:age], :gender=> params[:gender]})
 end

Now, in the above code, instead of using Names.last, i want to use Names.find_by_id(name_id). But how do I pass the name_id value between these methods?

Upvotes: 2

Views: 5089

Answers (3)

Anwuna
Anwuna

Reputation: 1113

There are several approaches to take in solving this problem but a fairly simple approach would be to pass the auto-generated id through a session variable e.g.

def welcome
    @name = params[:name]
    if @name 
       @record= Names.create({:name => @name})
       session[:id] =  @record.id
    end
end

def details
    @id = session[:id]
    @human = Names.find_by_id(@id)
end

Upvotes: 1

dandlezzz
dandlezzz

Reputation: 613

The easier way to do this, without relying on nested form is to put the id of the new record in the params of the detail get request. When the user clicks on details they need to go the details of their record.

So the route can include the id if you want something like names/:id/details.

your controller

def new    
 Names.create(params)
end

def edit
    @human = Names.find(params[:id])
    #whatever else
end

Without ajax you are pretty limited here. I can't produce the entire view code but if you have two views one that creates the new record and another that edits its details, you will be on the right track.

A more common pattern here would new/edit instead of new/details.

so in your routes file you just do resources :names. This will create the 7 restful routes. Read about it here, http://guides.rubyonrails.org/routing.html#singular-resources.

For your first day of rails you have the basics down, and following this pattern will help you a lot.

Upvotes: 2

Anand
Anand

Reputation: 3760

You could use a hidden_field in the welcome view form:

# views/.../welcome.html.erb
<%= form_for @user, action: :details, ...%>
  ...
  <%= f.hidden_field :name_id, value: @record.id %> 
<% end %>

# users_controller.rb
def details
  @human = Names.find(params[:name_id])
  ...
end 

Upvotes: 1

Related Questions