I am going through Hartl's Rails tutorial and have been stuck at a rather frustrating point in chapter 10.
<%= form_for(#micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new micropost..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
Using this yields this error
ActionView::Template::Error:
undefined local variable or method `object' for #<#<Class:0x00000106cad990>:0x00000103395f18>
I have been through it a few times and I am struggling to see where I am going wrong. I've referred to other SO posts but so far none have offered any solution.
Here is
_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
controller.rb
class MicropostsController < ApplicationController
before_action :signed_in_user
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
render 'static_pages/home'
end
end
def destroy
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
end
home controller
def home
#micropost = current_user.microposts.build if signed_in?
end
If i am passing 'object' as the argument through the partial it should work no?
Thanks
Related
I'm currently developing a client dashboard, there the client is able to see new offers, reservations and more.
The problem now is that I have a reservations controller and a dashboards controller
I want to display a pay button in my index.html.erb from the dashboards folder. For example:
<% #services.each do |service| %>
<%= form_for([#service, #service.reservations.new]) do |f| %>
<div class="col-12 col-sm-4">
<%= f.submit "Bestellen", class: "btn btn-primary", style: 'float:right' %>
</div>
<% end %>
<% end %>
But then I get the following error:
ActionView::Template::Error (undefined method `reservations' for nil:NilClass):
This is my reservations controller:
def create
service = Service.find(params[:service_id])
if current_user == service.user
flash[:alert] = "Du kannst nicht dein eigenes Angebot kaufen"
elsif current_user.stripe_id.blank?
flash[:alert] = "Füge eine Zahlungsmehtode hinzu"
return redirect_to payment_method_path
else
#reservation = current_user.reservations.build(reservation_params)
#reservation.service = service
#reservation.price = service.price
charge(service, #reservation)
end
redirect_to dashboard_path
end
My dashboards controller
def index
#services = Service.all
end
So I thought I would just create a file _form.html.erb in my reservations folder and then use <%= render 'reservations/form %> in my dashboards index, but this didn't work.
You need to use the loop variable instead of the undefined instance variable...
<% #services.each do |service| %>
<%= form_for [service, service.reservations.new] do |f| %>
<div class="col-12 col-sm-4">
<%= f.submit "Bestellen", class: "btn btn-primary", style: 'float:right' %>
</div>
<% end %>
<% end %>
I have a problem with my Rails blogging engine. Overall, the registration and creation of posts works (they form in the SQLite database), however when I attempt to list all the posts a user created, it throws a NoMethodError in User's show.html.erb view: undefined method 'title'.
PostsController.rb
class PostsController < ApplicationController
before_action :user_is_required, only: [:create, :destroy]
def index
#posts = Post.all
end
def new
#post = Post.new
end
def create
#post = user_logged_in.posts.create(post_params)
if #post.save
flash[:success] = "Your post has been successfully saved."
redirect_to root_path
else
flash[:danger] = "Oops! Something went wrong. Try again."
redirect_to new_post_path
end
end
def edit
end
def update
if #post.update_attributes(post_params)
flash[:success] = "Your post has been successfully updated."
redirect_to post_path(#posts)
else
flash[:danger] = "Oops! Something went wrong. Try again."
render 'post'
end
end
def show
#post = Post.find(params[:id])
end
def destroy
if #post.destroy
flash[:success] = "Your post has been successfully deleted."
redirect_to posts_path
else
flash[:danger] = "Oops! Something went wrong. Try again."
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
show.html.erb (User's view)
<div class="posts">
<div class="container marketing">
<div class="col-lg-4 col-md-4 col-xs-12 col-sm-12">
<section id="info">
<%= image_tag("#", :class => "user_avatar") %>
<h2 class="user_name">
<%= user_logged_in.name %>
</h2>
</section>
<% if user_logged_in %>
<%= link_to "Change avatar", class: "btn btn-primary" %><br>
<% end %>
<%= link_to "Follow", class: "btn btn-primary" %>
</div>
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
<h2>
<%= user_logged_in.name %> has <%= user_logged_in.posts.count %> posts.
</h2>
<% if user_logged_in.posts.any? %>
<% #posts.each do |post| %>
<h2 class="title">
<%= user_logged_in.posts.title %> # The line which raises the error
</h2>
<p class="post">
<%= user_logged_in.posts.content %>
</p>
<% end %>
<% end %>
</div>
</div>
post.rb
class Post < ActiveRecord::Base
belongs_to :user
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :title, presence: true
validates :content, presence: true
end
I am a newbie in Ruby on Rails and this is my first project. Any and all help will be highly appreciated.
Thanks in advance.
Think the logic is a bit confused here.
user_logged_in.posts is a relation, so it returns the posts associated with the user that's logged in.
#posts is set t all the posts in the table.
<% if user_logged_in.posts.any? %>
<% #posts.each do |post| %>
<h2 class="title">
<%= user_logged_in.posts.title %> # The line which raises the error
</h2>
<p class="post">
<%= user_logged_in.posts.content %>
</p>
<% end %>
<% end %>
This says that if the logged in user has any posts, loop through all of the posts (not just the users posts), and then I think you want to display the users posts, but you're going wrong with syntax. Try changing your code as follows:
<% if user_logged_in.posts.any? %>
<% user_logged_in.posts.each do |post| %>
<h2 class="title">
<%= post.title %>
</h2>
<p class="post">
<%= post.content %>
</p>
<% end %>
<% end %>
This will loop through the users posts, assigning each post to the post variable, and then displaying the title and content of that post.
posts should be post as you are inside loop i.e <%= user_logged_in.posts.title %> should be <%= post.title %> :
<% #posts.each do |post| %>
<h2 class="title">
<%= post.title %> # The line which raises the error
</h2>
<p class="post">
<%= post.content %>
</p>
<% end %>
else
object = record.is_a?(Array) ? record.last : record
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
object_name = options[:as] || model_name_from_record_or_class(object).param_key
apply_form_for_options!(record, object, options)
end
Hi, relatively new to Rails and programming in general. I'm getting this error when I try to submit a form with errors in them. It works perfectly fine when all the fields are filled in correctly, but if a form is missing something, it does not display the error like it should in this picture:
Instead, I get this:
Here is the code for the form:
<%= form_for(#quote) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Save a new quote..." %>
<%= f.text_field :author, placeholder: "Author:" %>
<%= f.text_field :source, placeholder: "Source:" %>
</div>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
Here is the code for the error messages:
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
And here is the code for the QuotesController:
class QuotesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def create
#quote = current_user.quotes.build(quote_params)
if #quote.save
flash[:success] = "Quote saved!"
redirect_to root_url
else
render 'static_pages/home'
end
end
def edit
end
def destroy
end
private
def quote_params
params.require(:quote).permit(:content, :author, :source)
end
end
How do I fix it so that it renders errors correctly like in the first picture?
* It turns out the code is actually working but the only problem is that the homepage of my site runs two forms that calls on the shared/error_messages which is why I'm guessing they conflict. When I remove one of the forms, the other form works fine. Any ideas on how to run two forms on the same page? *
I am trying to make a form that will create a new 'room'. However, when I push it to Heroku I am getting this error: 'We're sorry, but something went wrong.' I am using rails 4.1 and ruby 2.1.1. I am also using Heroku.
If it helps, I am kind of new to rails and am trying to port what I learned here to my new 'rooms' type.
This is my view/model/controller:
view: (app/views/rooms/index.html.erb)
<% if current_user %>
<h1>Create Room</h1>
<div class="Sign_Form">
<%= form_for(:room, :url => {:controller => 'rooms', :action => 'create'}) do |f| %>
<p> Created By:</br> <%= f.text_field :created_by%> </p>
<p> Name:</br> <%= f.text_field :name%> </p>
<p> Description:</br> <%= f.text_field :description%> </p>
<%= f.submit :Createroom %>
<% end %>
<% if #room.errors.any? %>
<ul class="Createroom_Errors">
<% for message_error in #room.errors.full_messages %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>
<h1>All Rooms</h1>
<% if #rooms.nil? %>
Rooms is nil
<% else %>
<% #rooms.each do |room| %>
<%= room.name %>
<% end %>
<% end %>
<% else %>
<%= render 'welcome' %>
<% end %>
Model: (app/model/room.rb)
class Room < ActiveRecord::Base
class << self
end
end
Controller: (app/controllers/rooms_controller.rb)
class RoomsController < ApplicationController
def index
#rooms = Room.all
end
def new
#room = Room.new
end
def create
#room = Room.new(params[:room])
if #room.save
flash[:notice] = "Room has been created!"
flash[:color] = "valid"
else
flash[:notice] = "Room has not been created!"
flash[:color] = "invalid"
end
render new
end
end
Any help would be highly appreciated. Thanks ahead of time.
EDIT: When I run it on localhost it says: undefined method `errors' for nil:NilClass.
I am trying to realize HABTM checkboxes following this tutorial:
http://www.justinball.com/2008/07/03/checkbox-list-in-ruby-on-rails-using-habtm/
While everything seems to work nicely the updates are not saved to my database.
My controller looks like the following:
class UserrolesController < ApplicationController
before_action :set_userrole
def edit
#projects=Project.all
end
def update
params[:userrole][:project_ids] ||= []
#userrole = Userrole.find(params[:id])
if #userrole.update_attributes(userrole_params)
flash[:notice] = "Settings have been saved."
redirect_to edit_userrole_url(#userrole)
else
flash.now[:error] = #userrole.errors
setup_form_values
respond_to do |format|
format.html { render :action => :edit}
end
end
end
private
def set_userrole
#userrole = Userrole.find(params[:id])
end
def userrole_params
params.require(:userrole).permit(:name, :project_ids)
end
end
My _form.html.erb like this:
<%= form_for(#userrole) do |f| %>
<% if #userrole.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#userrole.errors.count, "error") %> prohibited this person from being saved:</h2>
<ul>
<% #userrole.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="center">
<div class="field">
<%= f.label :Name %>
<%= f.text_field :name %>
</div>
<ul class="checkbox-list">
<% #projects.each do |project| -%>
<li><%= check_box_tag "userrole[project_ids][]", project.id, userrole_edits_project?(project) -%> <%= project.name -%></li>
<% end -%>
</ul>
<div class="actions">
<%= f.submit "Speichern", class: "btn btn-primary" %>
</div>
</div>
<% end %>
So I did everything like in the tutorial, the :name is saved without any problems, but the ids are not saved to the database. There is no error message. Does anybody has an idea what might go wrong? Maybe some missing permission somewhere?
So finally I found a work around for this problem.
I forced the update of project_ids by adding the following line in def update:
#userrole.project_ids=params[:userrole][:project_ids]