user3283997
user3283997

Reputation:

Rendering partials failing in rails 4

Here's the partial view I'm trying to render if an user is logged in

<div class='row'>

Post a project

<% form_for @project do |f| %>
<%= f.text_field :title, class:'form-control' %>
<%= f.text_area :brief, class: 'form-control' %>
<%= f.submit "Post" %>
<% end %>

In the main view when I try calling the partial, there's no error, but the partial doesn't render

<div class='col-lg-6'>
    <% if current_user %>
        <% render 'projects/new_project' %>
    <% end %>
</div>

This is my current_user method, defined in the application controller. I've also defined it as a helper method to use in a view template.

private
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

What am I doing wrong?

Upvotes: 1

Views: 75

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

You need to appreciate that <%= is an output tag

This means every time you want to output something in a non-native Ruby file (.erb etc), you'll have to use <%=

This is contrary to <% which does not output anything, but still performs the functions you specify


Partial

Also, you need to ensure your partial syntax is right:

#app/views/controller/you_view.html.erb
<%= render partial: "projects/new_project" %>

#app/views/projects/_new_project.html.erb
<%= form_for @project do |f| %>
    <%= f.text_field :title, class:'form-control' %>
    <%= f.text_area :brief, class: 'form-control' %>
    <%= f.submit "Post" %>
<% end %>

Upvotes: 0

vee
vee

Reputation: 38645

You want to render, you need to output the render's returned value using <%=...:

<%= render 'projects/new_project' %>

The expression(s) within the erb tags only get evaluated without the equals sign. In order to display the result of the expression, you need to include the equals sign; place your code within <%=...%>

Similarly, for you form_for call:

<%= form_for @project do |f| %>
...
<% end %>

Upvotes: 2

Related Questions