undefined local variable or method `post' - ruby-on-rails

Here is my form for my comments _form.html.erb:
<%= form_for([post, #comment]) do |f| %>
<p>
<%= f.text_area :body, placeholder: "Write a comment!" %>
</p>
<br>
<p> <%= f.submit %> </p>
<% end %>
and here is my posts form _form.html.erb:
<%= form_for #post, url: post_path(#post), method: :patch do |f| %>
<% if #post.errors.any? %>
<div id="errors">
<h2><%= pluralize(#post.errors.count, "Error") %> Prevent this post from posting</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :Edit_Post %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Here is my comments_controller.rb:
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.build(params[:comment])
#comment.save
redirect_to #posts
end
def destroy
#user = User.find(session[:user_id])
#posts = Post.find(params[:post_id])
#comment = #post.comments.find(params[:id])
#comment.destroy
redirect_to post_path(#post)
end
end
And here is my posts_controller.rb:
class PostsController < ApplicationController
before_action :load_post, only: [:show, :edit, :update, :destroy]
def index
#user = User.find(session[:user_id])
#posts = Post.all
end
def welcome
#user = User.find(session[:user_id])
#posts = Post.order("created_at desc").limit(4).offset(1)
#signed_in_user = session[:user_id]
end
def posts
#user = User.find(session[:user_id]) unless session[:user_id] == nil
redirect_to login_path, notice: "You're not logged in" unless #user
#signed_in_user = session[:user_id]
end
def new
#post = Post.new
#user = User.find(session[:user_id])
end
def create
#user = User.find(session[:user_id])
#post = Post.new(post_params)
#post.user_id = #signed_in_user
if #post.save
redirect_to dashboard_path
else
render 'new'
end
end
def show
#user = User.find(session[:user_id])
#signed_in_user = session[:user_id]
end
def edit
#user = User.find(session[:user_id])
end
def update
if #post.update(post_params)
redirect_to #post, notice: "Your post has been updated!"
end
end
def destroy
#user = User.find(session[:user_id])
#post.user_id = #signed_in_user
#post.destroy
redirect_to posts_path
end
private
def load_post
#post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:body)
end
end
Having this issue. Any help will be appreciated. Here is the picture of the error I am having:
EDIT: Here is my log
Started GET "/posts/24" for 127.0.0.1 at 2015-09-28 18:46:44 -0700
Processing by PostsController#show as HTML
Parameters: {"id"=>"24"}
[1m[36mPost Load (0.0ms)[0m [1mSELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1[0m [["id", 24]]
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
[1m[36mCACHE (0.0ms)[0m [1mSELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1[0m [["id", "24"]]
[1m[35m (0.0ms)[0m SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 24]]
Rendered comments/_form.html.erb (1.0ms)
Rendered posts/show.html.erb within layouts/application (7.0ms)
Rendered layouts/_nav.html.erb (1.0ms)
Completed 200 OK in 451ms (Views: 412.0ms | ActiveRecord: 1.0ms)

undefined local variable or method `post'
Your error message says it all. It tells you that, you don't have post defined in the corresponding controller action for your view. That's why you are getting that error.
So, you need to define #post (usually you use a instance variable in such cases) in the corresponding controller action i.e. PostsController's show action. You actually need to define #comment as well as you don't have it in your controller action currently. So, update your show method like this:
def show
#user = User.find(session[:user_id])
#signed_in_user = session[:user_id]
# you need to define #post and #comment
#post = Post.find params[:id]
#comment = Comment.new(post: #post)
end
Then, you can use #post and #comment in your view, so your comments/_form.html.erb would look like this:
<%= form_for([#post, #comment]) do |f| %>
. . .
. . .

Rails can pass instance variables from controllers to views, you should use #post replace post in conmments/_form.html.erb.
<%= form_for([#post, #comment = #post.comments.build]) do |f| %>

Related

Rails: Displaying a user post form_for on a user page with nested routes

I'm building a facebook clone, and I'm trying to have a text area on each user's page to allow them to make posts. I've tried a whole bunch of different things with no success, but right now I am getting this error when trying to access the user's show page:
First argument in form cannot contain nil or be empty
with this code:
Rails.application.routes.draw do
resources :friends, only: [:index, :destroy]
resources :posts
resources :friend_requests
devise_for :users
devise_scope :user do
root 'devise/sessions#new'
end
resources :users, only: [:index, :show] do
resources :posts
end
get 'about', to: 'static_pages#about'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
_post_form.html.erb
<%= form_for [#user, #post] do |f| %>
<%= f.text_area :content, size: "60x12", placeholder: "What do you want to say?" %>
<%= f.submit "Post" %>
<% end %>
class PostsController < ApplicationController
def index
#posts = Post.all
end
def new
#post = Post.new
#user = User.find(params[:user_id])
end
def create
#post = current_user.posts.build(post_params)
if #post.save
flash[:success] = "Posted!"
redirect_to user_path(current_user)
else
flash[:notice] = "Post could not be submitted"
redirect_to users_path
end
end
private
def post_params
params.require(:post).permit(:content)
end
end
class UsersController < ApplicationController
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
end
users/show.html.erb
<h4>You are signed in as <%= current_user.email %>! </h4>
<% if #user == current_user %>
<%= render "notifications" %>
<%= render 'shared/post_form' %>
<% end %>
<%= params.inspect %>
<%= current_user.id %>
server log:
Processing by UsersController#show as HTML
Parameters: {"id"=>"4"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 4], ["LIMIT", 1]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]]
Rendering users/show.html.erb within layouts/application
FriendRequest Load (0.5ms) SELECT "friend_requests".* FROM "friend_requests" WHERE "friend_requests"."friend_id" = $1 ORDER BY "friend_requests"."id" ASC LIMIT $2 [["friend_id", 4], ["LIMIT", 1000]]
Rendered users/_notifications.html.erb (2.0ms)
Rendered shared/_post_form.html.erb (3.0ms)
Rendered users/show.html.erb within layouts/application (10.2ms)
Completed 500 Internal Server Error in 23ms (ActiveRecord: 1.3ms)
ActionView::Template::Error (First argument in form cannot contain nil or be empty):
1: <%= form_for [#user, #post] do |f| %>
2: <%= f.text_area :content, size: "60x12", placeholder: "What do you want to say?" %>
3: <%= f.submit "Post" %>
4: <% end %>
app/views/shared/_post_form.html.erb:1:in `_app_views_shared__post_form_html_erb___99030300856795657_70237723952000'
app/views/users/show.html.erb:5:in `_app_views_users_show_html_erb___3196827877852207953_70237724137160'
Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack- 5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout
Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack- 5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.7ms)
Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack- 5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (5.0ms)
Rendering /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /usr/local/lib/ruby/gems/2.3.0/gems/actionpack- `5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (96.4ms)
You say that your form is having a problem rendering on the user's show page. If you have this form w/ nested resource setup like this:
form_for [#user, #post]
It means your form needs access to both the #user and the #post instance variable whereever the form is to be rendered. In this case, it is in the show action in your users controller. So your users controller should have something like this:
def show
#user = User.find(params[:id])
#post = #user.posts.build
end
I'm assuming your _post_form is loaded when you go to your posts#new route which is handled by this posts controller action:
def new
#post = Post.new
#user = User.find_by(id: params[:id])
end
Nested routes (in this case user > post) place the parent resource's id in the param resource_id, in you case it would be params[:user_id]. So, essentially, change this line:
#user = User.find_by(id: params[:id])
...to:
#user = User.find(params[:user_id])
That will access the correct id in the params and will cause an exception if no user was found (by using find instead of find_by), that will alert you to the any problem before you get to the view rendering. In your case the #user was nil and you got the form_for error you posted.
Update
I see from your logs you are going to the users#show action, which is this one:
def show
#user = User.find(params[:id])
end
as you can see, you're not setting the #post variable which you're passing to the form here:
form_for [#user, #post]
Add this to you action:
def show
#user = User.find(params[:id])
#post = Post.new
end

Rails Error - params not passing user id from controller

I'm building an Events app and I'm trying to create a link from the Event show page to the event creator's profile but I'm getting the following error -
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with 'id'=21
The error highlights this particular line of code in the Users Controller -
def show
#user = User.find(params[:id])
end
The development log produces this output -
Started GET "/users/21" for ::1 at 2016-04-15 12:37:08 +0100
Processing by UsersController#show as HTML
Parameters: {"id"=>"21"}
[1m[36mUser Load (0.1ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 8]]
[1m[35mUser Load (0.2ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 21]]
Completed 404 Not Found in 14ms (ActiveRecord: 0.9ms)
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=21):
app/controllers/users_controller.rb:14:in `show'
The user id (in this instance 5) is not being passed.I've tried numerous arguments in the show.html.erb page but none will work. Changing the show argument in the users controller to #user = current_user only succeeds in bringing up the profile of the user viewing the event and not the profile of the event creator.
Here's my code -
Events Controller
class EventsController < ApplicationController
before_action :find_event, only: [:show, :edit, :update, :destroy,]
# the before_actions will take care of finding the correct event for us
# this ties in with the private method below
before_action :authenticate_user!, except: [:index, :show]
# this ensures only users who are signed in can alter an event
def index
if params[:category].blank?
#events = Event.all.order("created_at DESC")
else
#category_id = Category.find_by(name: params[:category]).id
#events = Event.where(category_id: #category_id).order("created_at DESC")
end
# The above code = If there's no category found then all the events are listed
# If there is then it will show the EVENTS under each category only
end
def show
end
def new
#event = current_user.events.build
# this now builds out from a user once devise gem is added
# after initially having an argument of Event.new
# this assigns events to users
end
# both update and create actions below use event_params as their argument with an if/else statement
def create
#event = current_user.events.build(event_params)
# as above this now assigns events to users
# rather than Event.new
if #event.save
redirect_to #event, notice: "Congratulations, you have successfully created a new event."
else
render 'new'
end
end
def edit
# edit form
# #edit = Edit.find(params[:id])
#event = current_user.events.find(params[:id])
end
def update
if #event.update(event_params)
redirect_to #event, notice: "Event was successfully updated!"
else
render 'edit'
end
end
def destroy
#event.destroy
redirect_to root_path
end
private
def event_params
params.require(:event).permit(:title, :location, :date, :time, :description, :number_of_spaces, :is_free, :price, :organised_by, :organiser_profile, :url, :image, :category_id)
# category_id added at the end to ensure this is assigned to each new event created
end
def find_event
#event = Event.find(params[:id])
end
end
Users Controller -
class UsersController < ApplicationController
before_action :authenticate_user!
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = "Welcome to Mama Knows Best"
session[:uid] = #user.id
redirect_to root_path
else
render 'new'
end
end
def edit
#user = current_user
end
def update
#user = current_user
if #user.update(user_params)
flash[:success] = "Profile successfully updated!"
redirect_to root_path
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :username, :biography, :email, :url)
end
end
Show page -
<%= image_tag #event.image.url %>
<h1><%= #event.title %></h1>
<p>Location </p>
<p><%= #event.location %></p>
<p>Date</p>
<p><%= #event.date.strftime('%A, %d %b %Y') %></p>
<p>Time</p>
<p><%= #event.time.strftime('%l:%M %p') %></p>
<!-- above expresses date and time as per UK expectations -->
<p>More details</p>
<p><%= #event.description %></p>
<p>Number of Spaces available</p>
<p><%= #event.number_of_spaces %></p>
<% if #event.is_free? %>
<p>This is a free event</p>
<% else %>
<p>Cost per person</p>
<p><%= #event.price %></p>
<% end %>
<p>Organiser</p>
<p><%= #event.organised_by %></p>
<p>Organiser Profile</p>
<button><%= link_to "Profile", user_path %></button>
<p>Link to Organiser site</p>
<button><%= link_to "Organiser site", #event.url %></button>
<p>Submitted by</p>
<p><%= #event.user.name %></p>
<% if user_signed_in? and current_user == #event.user %>
<%= link_to "Edit", edit_event_path %>
<%= link_to "Delete", event_path, method: :delete, data: { confirm: "Are you sure?"} %>
<%= link_to "Back", root_path %>
<% else %>
<%= link_to "Back", root_path %>
<%= link_to "Book the Event", new_event_booking_path(#event) %>
<% end %>
routes -
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'registrations' }
resources :users
resources :events do
resources :bookings
end
# get 'welcome/index'
authenticated :user do
root 'events#index', as: "authenticated_root"
end
root 'welcome#index'
# the above method comes from devise and allows for the site to have a home page
# for users not signed in and one for when they are signed in
end
I haven't added anything relating to the users profile on the form partial as I didn't believe it to be relevant. Any help would be much appreciated.
To reiterate your question, you want a link on the event page that goes to the event organiser's profile page?
<p>Organiser Profile</p>
<button><%= link_to "Profile", user_path(#event.user) %></button>
user_path is a path helper in Rails which resolves to RESTful route of /users/:id. This goes in UserController#show and expects params hash to contain :id.
For your case, you are missing the argument. You need to do:
<button><%= link_to "Profile", user_path(current_user) %></button>
It automatically picks up id and passes it to params hash as : {:id => 7}
Doc
You may also want fix other such helpers call:
event_path
edit_event_path with appropriate argument.
What are you using for user authentication, devise or similar gem? Did you build your own? If so do you have current_user defined in the sessions helper? The below code is how current_user could be defined (a la Hartl Rails tutorial). This will allow you to use current_user in views and controllers.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
#current_user = user
end
end
end
I also noticed in your Users Controller under def create. I believe it should be session[:id] instead of session[:uid]. Please excuse me if this is not the case. Hope this helps.

Rails form_for edit not saving changes

I'm new to rails and having trouble getting my edit form to update attributes.
Here is my routes.rb for project and note:
resources :projects do
resources :notes
end
And this is my form_for in views/notes/edit.html.erb:
<%= form_for [#project, #note] do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :body %>
<%= f.text_area :body, rows: 10, class: "form-control" %>
</div>
<div class="action">
<%= f.submit "Save Note", class: "btn btn-success" %>
</div>
<% end %>
And finally this is my notes_controller.rb:
class NotesController < ApplicationController
before_action :find_note, only: [:show, :edit, :update, :destroy]
def index
#notes = Note.all
end
def new
#project = Project.find(params[:project_id])
#note = #project.notes.new
end
def create
#project = Project.find(params[:project_id])
#note = #project.notes.build(note_params)
#note.project = #project
#note.save ? flash[:notice] = "Note created." : flash[:error] = "Note could not be created, please try again."
redirect_to [current_user, #project]
end
def show
end
def edit
end
def update
if #note.update_attributes(note_params)
#note.save
flash[:notice] = "Note updated."
redirect_to authenticated_root_path
else
flash[:error] = "Could not update note."
render :edit
end
end
def destroy
#note.delete ? flash[:notice] = "Note deleted." : flash[:error] = "Note could not be deleted."
redirect_to user_project_path
end
private
def note_params
params.require(:note).permit(:title, :body)
end
def find_note
#project = Project.find(params[:project_id])
#note = #project.notes.find(params[:id])
end
end
This is what my terminal is outputting:
Started GET "/projects/12/notes/13/edit?utf8=%E2%9C%93&_method=patch&authenticity_token=vnIoOSi0ksMNI7uU0aMnBpkTBWi75wy%2BYvbs3RxO5sPIbvFzDA30%2B32dJxurdcsiu9zsIpuDCR%2FARUamBRrYmg%3D%3D&note%5Btitle%5D=Transporter+Materials&note%5Bbody%5D=Star+dust%2C+data&commit=Save+Note" for 127.0.0.1 at 2015-05-25 08:38:16 -0700
Processing by NotesController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"vnIoOSi0ksMNI7uU0aMnBpkTBWi75wy+Yvbs3RxO5sPIbvFzDA30+32dJxurdcsiu9zsIpuDCR/ARUamBRrYmg==", "note"=>{"title"=>"Transporter Materials", "body"=>"Star dust, data"}, "commit"=>"Save Note", "project_id"=>"12", "id"=>"13"}
Project Load (0.2ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1 [["id", 12]]
Note Load (0.2ms) SELECT "notes".* FROM "notes" WHERE "notes"."project_id" = ? AND "notes"."id" = ? LIMIT 1 [["project_id", 12], ["id", 13]]
Rendered notes/edit.html.erb within layouts/application (3.4ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Completed 200 OK in 328ms (Views: 296.4ms | ActiveRecord: 2.3ms)
Thanks in advance for any suggestions.
If you are using #project.notes.build(note_params).
No need of this #note.project = #project in create action
and in update
if you are using #note.update_attributes(note_params)
this is not required #note.save
and its better try to debug it using #note.update_attributes!(note_params)
it will give you why its not able to save.
<%= form_for [#project, #note], :url => project_note_path(#project,#note), :method => :put do |f| %>

form_for submitting as PostsController#show instead of create when creating comments(nested)

I'm trying to figure out why my form is submitting wrong. I'm trying to implement nested comments under posts and my form renders but submits to the wrong action. I've tried a few things but cannot get it to work. I can create a comment via the rails console but not through my form. I was going through a railscast where he uses a older version of rails. I figured the main difference would be strong parameters but it doesn't seem to be working and I can't figure out what I'm missing here. Thanks.
This is my log
Started GET "/posts/1?utf8=%E2%9C%93&authenticity_token=PJmmRV6hnY%2Bgm4cVe5LSdALHezbI3ehMkud0yYTaA%2FQ%3D&comment%5Bname%5D=Mark&comment%5Bemail%5D=hustada80%40gmail.com&comment%5Bcontent%5D=this+is+a+comment&commit=Create+Comment" for 127.0.0.1 at 2014-10-08 14:34:53 -0500
Processing by PostsController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PJmmRV6hnY+gm4cVe5LSdALHezbI3ehMkud0yYTaA/Q=", "comment"=>{"name"=>"Mark", "email"=>"hustada80#gmail.com", "content"=>"this is a comment"}, "commit"=>"Create Comment", "id"=>"1"}
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 1]]
Rendered comments/_form.html.erb (4.2ms)
Rendered comments/_comments.html.erb (0.1ms)
Rendered posts/show.html.erb within layouts/application (53.1ms)
Rendered layouts/_header.html.erb (0.5ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 524ms (Views: 519.7ms | ActiveRecord: 0.2ms)
Here is my form ( a partial _form)
<div class="well">
<h4>Leave a comment</h4>
<form role="form" class="clearfix">
<%= form_for([#commentable, #comment]) do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control', required: true %>
</div>
<div class="form-group">
<%= f.label :content %>
<%= f.text_area :content, class: 'form-control', required: true %>
</div>
<%= f.submit class: 'btn btn-primary' %>
<% end %>
</div>
Posts controller
class PostsController < ApplicationController
def new
#post = Post.new
end
def show
#post = Post.find(params[:id])
#commentable = #post
#comments = #commentable.comments
#comment = Comment.new
end
def index
#post = Post.all
#posts = Post.order('created_at DESC')
###posts_by_month = Post.find(:all, :order => 'created_at DESC').group_by { |post| post.created_at.strftime("%B %Y") }
end
def month_count
#posts_by_month = Post.find(:all, :order => 'created_at DESC').group_by { |post| post.created_at.strftime("%B %Y") }
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
private
def post_params
params.require(:post).permit(:title, :text)
end
Comments Controller
class CommentsController < ApplicationController
before_action :load_commentable
def index
#comments = #commentable.comments
end
def new
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(comments_params)
if #comment.save
redirect_to #commentable, notice: "Comment created."
else
render :new
end
end
def destroy
end
private
# def load_commentable
# resource, id = request.path.split('/')[1, 2]
# #commentable = resource.singularize.classify.constantize.find(id)
# end
def load_commentable
klass = [Post].detect { |c| params["#{c.name.underscore}_id"]}
#commentable = klass.find(params["#{klass.name.underscore}_id"])
end
def comments_params
params.require(:comment).permit(:content, :email, :name)
end
end
routes
Rails.application.routes.draw do
root 'posts#index'
get "sign_up" => "users#new", :as => "sign_up"
get "/log-in" => "sessions#new"
post "/log-in" => "sessions#create"
get "/log-out" => "sessions#destroy", as: :log_out
resources :posts do
resources :comments
end
resources :users
resources :sessions
Try something like
<%= form_for([#commentable, #comment], url: post_comments_path, method: :post) do |f| %>

Message_controller with Ancestry Gem

Apologies for the newbie question but, I'm getting the following error referencing message#new action in my Messages controller:
ActiveRecord::RecordNotFound (Couldn't find User without an ID): app/controllers/messages_controller.rb:18:in `new'
#recipient = User.find(params[:user_id])
I'm trying to incorporate the ancestry gem in my messages_controller, specifically, when I try to reply to a message that has been received in the user inbox(index.html.erb). I understand that there is currently no ID being passed, but does anyone encountered a similar issue? Code below:
class MessagesController < ApplicationController
def index
#messages = current_user.to_messages
end
def outbox
type = (params[:type] && params[:type] == "sent" ) ? "from_messages" : "to_messages"
#messages = current_user.from_messages
end
def show
#message = Message.find params[:id]
end
def new
#message = Message.new(:parent_id => params[:parent_id])
#recipient = User.find(params[:user_id])
end
def create
#message = Message.new message_params
#message.sender_id = current_user.id
if #message.save
flash[:success] = "Your message has been sent!"
redirect_to users_path
else
flash[:failure] = "Please try again."
redirect_to users_path
end
end
def destroy
#message = Message.find(params[:id])
#message.destroy
redirect_to messages_path
end
private
def message_params
params.require(:message).permit(:content, :sender_id, :recipient_id, :parent_id)
end
end
show.html.erb (view)
From: <%= link_to #message.recipient.first_name + " " + #message.recipient.last_name, user_path(#message.recipient.id) %>,
To: <%= #message.sender.first_name + " " + #message.sender.last_name %>,
Message: <%= #message.content %>
<% if #message.recipient_id == current_user.id %>
<%= link_to "Reply", new_message_path(:parent_id => #message) %>
<% end %>
Started GET "/messages/new?parent_id=19" for 127.0.0.1 at 2014-09-27 15:41:18 -0400
Processing by MessagesController#new as HTML
Parameters: {"parent_id"=>"19"}
Message Load (0.1ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = ? LIMIT 1 [["id", 19]]
Completed 404 Not Found in 11ms
ActiveRecord::RecordNotFound (Couldn't find User without an ID):
app/controllers/messages_controller.rb:18:in `new'
Rendered /Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)
Rendered /Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.0ms)
Rendered /Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (13.8ms)
I'm not sure about the recipient/sender issue, but I think you just need to pass user_id as a param from your view. So the link_to would become: <%= link_to "Reply", new_message_path(:parent_id => #message, :user_id => #message.recipient_id) %>. This will make it available in the new action.

Resources