Rails 5: Access create method from another controller - ruby-on-rails

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 %>

Related

NoMethodError in Users#show, undefined method `title' for #<Post::ActiveRecord_Associations_CollectionProxy:0x00000004c5e5f0>

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 %>

Heroku "Something Went Wrong" when trying to create a new form

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.

Rails: Two different NoMethodError's when trying to display files

I'm making a basic application and I made it so a user can attach a file to a form post. That all works perfectly fine, but now I'm trying to display a link to the file and it doesn't seem to work.
I'm getting two errors. One if I attach a file and another if I don't attach a file. They both say undefined method 'doc=' for nil:NilClass but are on different lines of code.
If I don't upload a file this is what I get: NoMethodError in Projects#index on this line of code <% if #project.doc %>.
If I do upload a file this is what I get: NoMethodError in ProjectsController#create on this line of code #project.doc = uploaded_io.original_filename
projects_controller.rb
class ProjectsController < ApplicationController
def index
#projects = Project.all
end
def show
end
def new
#projects = Project.new
end
def create #no view
#projects = Project.new(project_params)
uploaded_io = params[:doc]
if uploaded_io.present?
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
#project.doc = uploaded_io.original_filename
end
end
if #projects.save
redirect_to projects_path, :notice => "Your project was sent!"
else
render "new"
end
end
def edit
#projects = Project.find(params[:id])
end
def update #no view
#projects = Project.find(params[:id])
if #projects.update_attributes(project_params)
redirect_to projects_path, :notice => "Your project has been updated."
else
render "edit"
end
end
def destroy #no view
#projects = Project.find(params[:id])
#projects.destroy
redirect_to projects_path, :notice => "Your project has been deleted."
end
private
def project_params
params.require(:project).permit(:title, :description)
end
end
index.html.erb
<div class="container">
<div class="page-header">
<h1>Projects<small> Here are all of your projects.</small></h1>
</div>
</div>
<% #projects.each do |project| %>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<%= project.title %>
</div>
</div>
<div class="panel-body">
<p>
<%= project.description %>
</p>
<br>
<%= link_to "Discuss", new_project_discussion_path(project) %> |
<%= link_to "Tasks", new_project_task_path(project) %> |
<%= link_to "Edit", edit_project_path(project) %> |
<%= link_to "Delete", project, :method => :delete %>
<% if #project.doc %>
<p>Document: <%= link_to #project.doc, "/uploads/#{#project.doc}", :target => "_blank" %></p>
<% end %>
</div>
</div>
<%end%>
<br>
<br>
<div class="container">
<p><a class="btn btn-primary btn-lg" href="/projects/new" role="button">Create project</a></p>
</div>
_form.html.erb
<%= form_for(#projects, :html => { :multipart => true}) do |f| %>
<% if #projects.errors.any? %>
<ul>
<% #projects.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<div class="container">
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<%= label_tag :doc, 'Files (optional)' %>
<%= file_field_tag :doc %>
<br>
<div class="form-group">
<%= f.submit "Submit Project", class: "btn btn-primary" %>
</div>
<% end %>
Updated :
You have many errors, here are a few that I found :
uploaded_io = params[:doc]
Should be
uploaded_io = params[:project][:doc]
Also delete this line
#project.doc = uploaded_io.original_filename
You don't need that.
Finally, in your views, you should have project.doc instead of #project.doc

using partials in Hartl's Rails tutorial, undefined variable method 'object'

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

RAILS HABTM checkboxes don't update

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]

Resources