jdesilvio
jdesilvio

Reputation: 1854

Rails 4 - Render controller variable

I'm a Rails newbie and this seems like a trivial thing, but I can't figure out how to render this.

I have a form that takes in a string input:

<%= form_for @idea do |f| %>
  <div>
    <%= f.label :idea_list %>
    <%= f.text_field :idea_list %>
  </div>
  <%= f.submit %>
<% end %>

And a controller:

class IdeasController < ApplicationController
  def index
  end

  def new
    @idea = Idea.new
  end

  def create
    @idea = Idea.new(idea_params)

    if @idea.save
      render :index
    else
      render 'new'
    end
  end

  private

  def idea_params
    params.require(:idea).permit(:idea_list)
  end
end

I then want to render the idea_list parameter in index.html.erb, but cannot figure out how to do so. I've tried:

<p><%= @idea %></p>

but I get an output of #<Idea:0x007f8b16d98638>.

<% @idea do |idea| %>
  <p><%= idea.idea_list %></p>
<% end %>

I've tried many variations of this but keep getting various errors.

Please help.

Upvotes: 0

Views: 42

Answers (1)

creativereason
creativereason

Reputation: 1524

So @idea is an instance of an object. idea_list is an attribute. So you need to call @idea.idea_list. Any time you want to reference an instance of an object / model from a controller it's going to @instance.attribute.

In your case, it's going to be

<p><%= @idea.idea_list %></p>

If you want to show them from a list of the all, in your view it's

<%@ideas.each do |idea| %>
  <p><% idea.idea_list%></p>
<% end%>

And in your controller it's

def index 
  @ideas = Idea.all
end

Upvotes: 1

Related Questions