I just finished Hartl’s RoR tutorial and am now trying to mess around with some more stuff.
Specifically: I’m trying to allow the user to create microposts on any page, by rendering the micropost partial in the header.html.erb file (which is rendered on every page).
the partial:
<%= form_for(@micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "micropost" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
Doing this has resulted in the error on line #1 of the partial: undefined method 'model_name' for NilClass:Class on any page which I have not fixed by adding @micropost = current_user.microposts.build in the controller method that links to said view. For example:
#in controllers/static_pages_controller.rb
def about
if signed_in?
@micropost = current_user.microposts.build
end
end
Would fix this error when I visit the about page
I’ve been trying to figure out a way to do a “blanket fix” that will work on all pages without me having to paste in the declaration everywhere, any ideas?
You don’t need to use the
form_forbuilder here; Rails also provides aform_taghelper for more generic forms:This way, you don’t need to build the object when loading every page, but
microposts#createcan still pull data fromparams[:micropost]. See here for more info.