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.
Related
I am building my first RoR application and it involves Assignments with Tasks. The user has the ability to Create Assignments, add Tasks to those assignments, and also mark assignments complete. I have an "Accomplishments" page that show cases a featured User with "most completed" assignments (User that has more than 5 assignments completed). Where my problem lies is that the User doesn't change as the assignments completed count does. Currently I only have 2 users. User1 has completed 8 assignments, User2 has completed 7 assignments. User2 is being displayed as the "Featured User with most completed assignments".
My code is as follows:
Assignments Controller
class AssignmentsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_assignment, only: [:show, :edit, :update,
:destroy]
#GET/ASSIGNMENTS
def index
user = User.find params[:user_id]
#incomplete_assignments = user.assignments.incomplete
#complete_assignments = user.assignments.complete
end#index
def new
#assignment = current_user.assignments.build
#assignment.tasks.build
end#new
#POST
def create
#assignment = current_user.assignments.build(assignment_params)
if #assignment.save
redirect_to [current_user, #assignment], notice: "Assignment was created successfully!"
else
render :new
end
end #create
def show
##user = current_user.assignments
#task = Task.new
end#show
#PATCH
def edit
end
def update
#assignment.update(assignment_params)
redirect_to [current_user, #assignment], notice: "Assignment updated successfully!"
end#update
#DELETE
def destroy
#assignment.destroy
redirect_to [current_user, #assignment], notice: "Assignment was deleted successfully!"
end #destroy
def completed
Assignment.where(id: params[:assignment_ids]).update_all(status: true)
redirect_to user_assignments_path(current_user.id)
end#completed
private
#STRONG PARAMS
def set_assignment
#assignment = Assignment.find(params[:id])
end
def assignment_params
params.require(:assignment).permit(:name, :due_date, task_attributes: [:name])
end
end#class
Users Controller
class UsersController < ApplicationController
before_action :authenticate_user!
def show
#user = User.find(params[:id])
#assignment = Assignment.new
redirect_to user_path(#user)
end
def show_completed
#users = User.all
end
end
My view with Accomplishments
<h3> Status of who has done what</h3>
<br>
<% for user in #users %>
<%= user.email %> has completed <%= user.assignments.count %> assignments. <br>
<% end %>
<% if user.assignments.complete.count > 5 %>
<h1> **Featured User** </h1>
<h2><%= user.email %> has completed the most assignments!</h2>
<% else %>
<p> Not enough completed Assignments to be featured!</p>
<% end %>
<%= link_to 'Back to your asssignments', user_assignments_path(current_user, #assignment) %>
This may be a matter of a misunderstanding on how to properly use .count in a method, or something as simple as that in my View where I say display the user with assignments greater than 5 my application is doing just that.
I'm building a Rails app which allows users to create and book onto events. I've integrated the twitter omniauth gem along with devise. It logs me in correctly and redirects back however when I click on the link to create an event or book an event the app redirects me back to the sign in page. I've set the site up so that only signed in users can do this but it doesn't appear to cover the omniauth integration.
I also have no way to sign-out from one user to another if I use Twitter to sign in. I want to add Facebook auth also but want to fix this first. What code (inc. validations) am I missing to cover these functions?
Here's the relevant code so far -
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, :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
Application controller -
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:account_update) << :name
end
# the application controller
# handles everything across the site
# make the current_user AND the logged_in? available to
# be used in the views as well as the controllers
helper_method :current_user
helper_method :logged_in?
helper_method :logged_out?
def current_user
# this is who I am signed in as
#current_user = User.find(session[:uid])
end
def logged_in?
# am i logged in?
# do i have a cookie called uid?
session[:uid].present?
end
def make_sure_logged_in
# If I'm not logged in, redirect me to the log in page
if not logged_in?
flash[:error] = "You must be signed in to see that page"
redirect_to new_session_path
end
end
def logged_out?
session[:uid] = nil
flash[:success] = "You've logged out"
redirect_to root_path
end
end
index.html.erb - events
<header>
<div class="category">
<%= link_to image_tag('MamaKnows.png'), root_path, id: "home" %>
<% Category.all.each do |category| %>
<li><%= link_to category.name, events_path(category: category.name) %></li>
<% end %>
<!-- The code loop above creates category links to the home page -->
</div>
<nav id="nav">
<% if logged_in? %>
<%= link_to 'Create Event', new_event_path %>
<%= link_to 'Account', user_path(current_user) %>
<%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>
<% else %>
<%= link_to "Create an Event", new_user_session_path %>
<% end %>
</nav>
</header>
<% #events.each do |event| %>
<%= link_to (image_tag event.image.url), event %>
<h2><%= link_to event.title, event %></h2>
<h2><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h2>
<% end %>
OmniauthCallback Controller
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def twitter
#details = request.env["omniauth.auth"]
#provider = #details["provider"]
#provider_id = #details["uid"]
#user = User.where(provider: #provider, provider_id: #provider_id).first
if #user.present?
#sign them in
else
# make a new user
#user = User.new
#user.provider = #provider
#user.provider_id = #provider_id
# because of has_secure_password - will this work?
#user.password = "AAAAAA!!"
#user.password_confirmation = "AAAAAA!!"
# let's save the key and secret
#user.key = #details["credentials"]["token"]
#user.secret = #details["credentials"]["secret"]
# lets fill in their details
#user.name = #details["info"]["name"]
if #provider == "twitter"? #user.save!(:validate => false) : #user.save!
# the above if statement allows for twitter to skip validation which requires an email
#user.email = #details["info"]["email"]
end
#user.save!
end
session[:uid] = #user.id
flash[:success] = "You've signed in"
redirect_to root_path
end
def password_required?
super && provider.blank?
end
end
Any assistance would be appreciated.
I am new to rails. I have defined controller for the index of shop_products as follows
shop_profile.rb
class ShopProfile < ActiveRecord::Base
has_and_belongs_to_many :users
has_one :shop_inventory_detail
end
shop_product.rb
class ShopProduct < ActiveRecord::Base
belongs_to :shop_profile
end
shop_products_controller.rb
class ShopProductsController < ApplicationController
def index
#shop_profile = ShopProfile.find(params[:shop_profile_id])
#products = #shop_profile.shop_products
end
end
index.html.erb in shopprofiles
<%= link_to 'All Products', shop_profile_shop_products_path(#shop_profile) ,class: 'btn btn-primary' %>
on this line I get error that
ActionController::UrlGenerationError in ShopProfiles#index
Showing /home/mindfire/Desktop/project/training/Rails/grocery-shop/app/views/shop_profiles/index.html.erb where line #4 raised:
No route matches {:action=>"index", :controller=>"shop_products", :shop_profile_id=>nil} missing required keys: [:shop_profile_id]
the routes
shop_profile_shop_products GET /users/shop_profiles/:shop_profile_id/shop_products(.:format) shop_products#index
POST /users/shop_profiles/:shop_profile_id/shop_products(.:format) shop_products#create
new_shop_profile_shop_product GET /users/shop_profiles/:shop_profile_id/shop_products/new(.:format) shop_products#new
edit_shop_profile_shop_product GET /users/shop_profiles/:shop_profile_id/shop_products/:id/edit(.:format) shop_products#edit
shop_profile_shop_product GET /users/shop_profiles/:shop_profile_id/shop_products/:id(.:format) shop_products#show
PATCH /users/shop_profiles/:shop_profile_id/shop_products/:id(.:format) shop_products#update
PUT /users/shop_profiles/:shop_profile_id/shop_products/:id(.:format) shop_products#update
DELETE /users/shop_profiles/:shop_profile_id/shop_products/:id(.:format) shop_products#destroy
And when I pass the shop_profile_id manually I get the desired page.
Thanks in advance for any help.
shop_profiles_controller.rb
class ShopProfilesController < ApplicationController
before_action :authenticate_user!, except: :show
after_action :verify_authorized, only: :shop_index
def new
#shop = ShopProfile.new
end
def index
#shops = current_user.shop_profiles
end
def show
#shop_profile = ShopProfile.find_by(id: params[:id])
#items = #shop_profile.shop_products.group(:category_id).where(category_id: params[:category_id])
end
def create
#shop = ShopProfile.new(shop_params)
#shop.build_address(address_params_shopkeeper)
if current_user.shop_profiles << #shop
flash[:success] = 'Shop Details added'
redirect_to root_path
else
flash[:error] = 'Shop Details not added'
render 'new'
end
end
def edit
#shop = current_user.shop_profiles.find_by(id: params[:id])
end
def update
#shop = current_user.shop_profiles.find_by(id: params[:id])
if #shop.update_attributes(shop_params) and #shop.address.update_attributes(address_params_shopkeeper)
flash[:success] = 'Updated Successfully'
redirect_to shop_profiles_path
else
flash[:danger] = 'Shop Details not Updated'
render 'edit'
end
end
end
But I think it has nothing to do with shop_profiles_controller.
I was calling the shop_product index page from there.
error log
Started GET "/users/shop_profiles" for 127.0.0.1 at 2016-03-31 16:36:34 +0530
Processing by ShopProfilesController#index as HTML
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 ORDER BY `users`.`id` ASC LIMIT 1
Rendered shop_profiles/index.html.erb within layouts/application (2.3ms)
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.4ms)
ActionView::Template::Error (No route matches {:action=>"index", :controller=>"shop_products", :shop_profile_id=>nil} missing required keys: [:shop_profile_id]):
1: <div>
2: <%= link_to 'Add Shop' ,new_shop_profile_path, class: 'btn btn-primary' %>
3: <%= link_to 'Add New Product', new_product_path, class: 'btn btn-primary', method: :get %>
4: <%= link_to 'All Products', shop_profile_shop_products_path(#shop_profile) ,class: 'btn btn-primary' %>
5: </div>
6: <div>
7: <% if !#shops.nil? %>
app/views/shop_profiles/index.html.erb:4:in `_app_views_shop_profiles_index_html_erb___2474323268141556614_25251260'
Rendered /home/mindfire/.rvm/gems/ruby-2.2.0#localshop/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (9.0ms)............
Thanks #Зелёный
From your error log, it looks you are trying to send a nil in shop_profile_shop_products_path which is causing the issue.
Make sure #shop_profile is not nil.
You can do the followings if you want to avoid this issue:
<%= link_to 'All Products', shop_profile_shop_products_path(#shop_profile) ,class: 'btn btn-primary' if #shop_profile.present? %>
Hope it solves your problem!
Thanks you all for your responses .
The problem was a user can have multiple shop profiles . So I iterate through all shop profiles and call the index method and got the desired page.
In my rails app , when I logout , in the destroy method I am setting session[:user_id]=nil. But when I press back button on the browser the session[:user_id] gets back its previous value and it is automatically showing the logged in page. Why is this happening? How do I make the session[:user_id]=nil persistent till I change it?
session_controller.rb
class SessionsController < ApplicationController
def index
end
def show
end
def new
end
def create
#user = User.find_by_email(params[:email])
if #user && #user.authenticate(params[:password])
session[:user_id] = #user.id
redirect_to user_posts_path
else
render 'new'
end
end
def destroy
session[:user_id] = nil
end
end
application.html.erb
<% if !(session[:user_id].nil?)%>
Logged in as <%= current_user.email %>
<%= link_to 'Log Out', session_path(current_user), :method => :delete %>
<% else %>
<% if current_page?(new_user_path) %>
<%= link_to "Log in", login_path %>
<% elsif current_page?(login_path) %>
<%= link_to "sign up",new_user_path%>
<% else %>
<%= link_to "Log in", login_path %>
<%= link_to "sign up",new_user_path%>
<% end %>
<% end %>
<%= yield %>
there is no error in the rails s console.
last message on the console.
Started DELETE "/sessions/2" for 127.0.0.1 at 2015-10-08 00:23:11 +0530
Processing by SessionsController#destroy as HTML
Parameters: {"authenticity_token"=>"B0QLdVrsV9ZgwjS/Y8qVb3ID0q9gsC2peFQAZ/0J638kUTpXcAYcg1I+ulX1UaLujr4C7NPgIann74UETMOz6w==", "id"=>"2"}
Rendered sessions/destroy.html.erb within layouts/application (0.1ms)
Completed 200 OK in 144ms (Views: 143.4ms | ActiveRecord: 0.0ms)
Use reset_session in your logout action instead. This will issue a new session identifier and declare the old one invalid and prevents other session fixation based attacks.
http://guides.rubyonrails.org/security.html#session-fixation-countermeasures
This is a run through of how to setup your SessionsController properly:
Sessions are not really like a standard crud resource where you have the full range of CRUD verbs and fetch records from the database.
From a user standpoint there are only three actions:
new - displays the login form
create - verifies the credentials and signs the user in.
destroy - logs user out by resetting the session.
Change your routes definition to treat Sessions as a singular resource:
resource :sessions, only: [:new, :create, :destroy]
Then we are going to create a helper:
module SessionsHelper
def current_user
#user ||= User.find!(session[:user_id]) if session[:user_id]
end
def user_signed_in?
!current_user.nil?
end
def can_sign_in?
user_signed_in? || current_page?(new_user_path) || current_page?(new_session_path)
end
end
This way the actual implementation of how the user is stored in the session is only in one place in your application and not spread all over your controllers and views.
Lets make sure we can call it from our controllers:
class ApplicationController < ActionController::Base
include SessionsHelper
end
Then lets remedy the controller:
class SessionsController < ApplicationController
# GET /session
def new
end
# POST /session
def create
reset_session # prevents sessions fixation!
#user = User.find_by(email: params[:email])
if #user && #user.authenticate(params[:password])
session[:user_id] = #user.id
redirect_to user_posts_path
else
render 'new', flash: "Invalid username or password."
end
end
# DELETE /session
def destroy
reset_session
if user_signed_in?
flash[:notice] = 'You have been signed out successfully.'
else
flash[:error] = 'You are not signed in!'
end
redirect_to root_path
end
end
application.html.erb
<%= render partial: 'sessions/actions' %>
<%= yield %>
We use a partial since the application layout tends to turn into a monster.
sessions/_actions.html.erb.
<% if user_signed_in? %>
Logged in as <%= current_user.email %>
<%= link_to 'Log Out', session_path, method: :delete %>
<% else %>
<%= link_to 'Log in', new_session_path if can_sign_in? %>
<% end %>
I'm building a rails 4.2.0 app with a contact us page (this page does have a semi-empty controller). I'm trying to embed a form partial from another controller.
Here is the code (minus the text):
<% if user_signed_in? %>
<% render 'enquiries/form' %>
<% end %>
When I run this I get the error 'First argument in form cannot contain nil or be empty'.
My enquiries form looks like a basic rails form:
<%= form_for #enquiry do |f| %>
<% if #enquiry.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#enquiry.errors.count, "error") %> prohibited this enquiry from being saved:</h2>
<ul>
<% #enquiry.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :subject, "Subject:" %><br>
<%= f.text_field :subject %>
</div>
<div class="field">
<%= f.label :e_description, "Description:" %><br>
<%= f.text_area :e_description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
What could be the possible reason for the error? Or is there a better way of embedding a view into another?
Update/Edit:
Here's the routes:
devise_for :users
resources :rooms do
resources :viewings
end
resources :rmcats
resources :extras
resources :extracats
resources :enquiries
root :to => redirect('/pages/home')
get 'pages/home'
get 'pages/contactus'
And the enquiry controller:
class EnquiriesController < ApplicationController
before_action :set_enquiry, only: [:show, :edit, :update, :destroy]
# GET /enquiries
def index
#enquiries = Enquiry.all
end
# GET /enquiries/1
def show
end
# GET /enquiries/new
def new
#enquiry = Enquiry.new
end
# GET /enquiries/1/edit
def edit
end
# POST /enquiries
def create
#enquiry = Enquiry.new(enquiry_params)
if #enquiry.save
redirect_to #enquiry, notice: 'Enquiry was successfully created.'
else
render :new
end
end
# PATCH/PUT /enquiries/1
def update
if #enquiry.update(enquiry_params)
redirect_to #enquiry, notice: 'Enquiry was successfully updated.'
else
render :edit
end
end
# DELETE /enquiries/1
def destroy
#enquiry.destroy
redirect_to enquiries_url, notice: 'Enquiry was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_enquiry
#enquiry = Enquiry.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def enquiry_params
params.require(:enquiry).permit(:subject, :e_description)
end
end
This is the pages controller:
class PagesController < ApplicationController
around_filter :resource_not_found
# def home
# end
private
# If resource not found redirect to root and flash error.
# => For pages this will rarely be needed as it should 404.
def resource_not_found
yield
rescue ActiveRecord::RecordNotFound
redirect_to root_url, :notice => "Page not found."
end
end
Edit:
Log:
Started GET "/pages/contactus" for ::1 at 2015-03-21 01:05:25 +0000
Processing by EnquiriesController#new as HTML
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Rendered enquiries/_form.html.erb (0.0ms)
Rendered pages/contactus.html.erb within layouts/application (0.0ms)
Completed 200 OK in 235ms (Views: 234.6ms | ActiveRecord: 0.0ms)
It is telling you that #enquiry is nil at the time it is trying to render the form. You need to call the new action to create the #enqiury for the form to represent.
You could change your route to:
get 'pages/contactus' => 'enquiries#new'
Then in your Enquiry controller:
def new
#enquiry = Enquiry.new
render 'pages/contactus'
end
EDIT:
Ok, so now we combine what Friends Systems put in his answer:
<% if user_signed_in? %>
<%= render 'enquiries/form' enquiry: #enquiry %>
<% end %>
And now change any instance of #enquiry in the form to enquiry
This is because you need to pass the variable to the partial.
the problem is, that your #enquiry variable is not defined in the context you are rendering the partial.
its not defined by the controller action that gets called, you should create a instance of Enquiry by calling
#enquiry = Enquiry.new
in your action.
In Addition
to use it somewhere else i would pass the #enquiry instance variable as a locale variable to the partial
<% render 'enquiries/form', :enquiry => #enquiry %>
your form method should then look like this:
<%= form_for enquiry do |f| %>
...
<% end %>
of course all the instances vars should be replaced then. just remove the '#'
EDIT:
According to your controller setup you posted above the best way would be to use something like
#enquiry ||= Enquiry.new
in your form partial to make shure a new instance is created if #enquiry is nil.