darkginger
darkginger

Reputation: 690

Creating if condition in Rails form based on page params

I am prepopulating a value in a Rails form based on an attribute from a table.

Using a normal Scaffold, this works great for the new action. When I return to edit though, it pre-populates an incorrect value. To fix this, I want to create an if/else condition in the form. For testing, if we are in the edit route, I want the form to put an integer value of "7" (as a test):

<% if params[:edit] %> 
  <div class="form-group">
     <div class="field">
      <%= f.label :Game_Number %><br>
      <%= f.number_field :category_id, :value => 7, class: "form-control" %>
    </div>
  </div>
<% else %> 
    <div class="form-group">
     <div class="field">
      <%= f.label :Game_Number %><br>
      <%= f.number_field :category_id, :value => params[:id].to_i, class: "form-control" %>
    </div>
  </div>

<% end %> 

The page loads when doing so, but it continues to use the <% else %> action incorrectly.

Also, the URL structure for this edit page from my scaffold is like so:

http://localhost:3000/questions/22/edit

How should I frame that if condition to alter behavior on the edit route?

Upvotes: 1

Views: 1974

Answers (3)

Gourav
Gourav

Reputation: 576

<% if @question.persisted? %> 
  <div class="form-group">
     <div class="field">
      <%= f.label :Game_Number %><br>
      <%= f.number_field :category_id, :value => 7, class: "form-control" %>
    </div>
  </div>
<% else %> 
    <div class="form-group">
     <div class="field">
      <%= f.label :Game_Number %><br>
      <%= f.number_field :category_id, :value => params[:id].to_i, class: "form-control" %>
    </div>
  </div>

<% end %>

Upvotes: 0

lei liu
lei liu

Reputation: 2775

Use instance variable to do this, set the value in controller, not in view, in your controller:

def new
  @object = Object.new(category_id: params[:category_id])
end

def edit
  @object = Object.find(params[:id])
  // puts @object.category_id => 7 or what
end

In your view, just:

   <%= form_for @object do |f| %>
     <div class="form-group">
         <div class="field">
          <%= f.label :Game_Number %><br>
          <%= f.number_field :category_id, class: "form-control" %>
        </div>
      </div>
   <% end %>

Upvotes: 0

dp7
dp7

Reputation: 6749

You get action and controller in your params. You can have such a condition:

<% if params[:action] == 'edit' %>
<% else %>
<% end %> 

Upvotes: 2

Related Questions