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.
Related
I am following a guide to build a blog with rails, simple Post model with title and body.
I am using simple form and upon form submission to create a new post, the post saves created_at and updated_at values, but not the actual content submitted in the form.
I have attempted removing the code for simple form and using Rails native form_for. This DOES save all values to the database. I am new to simple form, not certain whether or not I am using it correctly.
Here is the console record:
Started POST "/posts" for ::1 at 2019-08-17 13:51:01 -0500
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qY8kYZxVIMBL8lzHYuQ4qOu6nXsTGLWCRhLPJ2eiAU8EyzR61fZppAFBYmgcm3rx02FYAHcCgFBVlUyDTLtDGA==", "post"=>{"title"=>"Simple Form Test", "body"=>"<p>Test Test Test</p>\r\n"}, "commit"=>"Create Post"}
(0.0ms) begin transaction
SQL (3.3ms) INSERT INTO "posts" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2019-08-17 18:51:01.325736"], ["updated_at", "2019- 08-17 18:51:01.325736"]]
(7.7ms) commit transaction
Redirected to http://localhost:3000/posts/3
Completed 302 Found in 28ms (ActiveRecord: 11.1ms)
Here is the form:
<%= simple_form_for #post do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2>
<%= "#{pluralize(#post.errors.count, "error")} prohibited this post from being saved:" %>
</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li>
<%= msg %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.input :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.input :body, :as => :ckeditor, input_html: {:ckeditor => {:toolbar => 'FULL'}}, class: "form-control" %>
</div>
<div class="form-group">
<%= f.button :submit %>
</div>
<% end %>
Here is the controller:
class PostsController < ApplicationController
before_action :find_post, only: [:edit, :update, :show, :delete]
# Index action to render all posts
def index
#posts = Post.all
end
# New action for creating post
def new
#post = Post.new
end
# Create action saves the post into database
def create
#post = Post.new
if #post.save(post_params)
flash[:notice] = "Successfully created post!"
redirect_to post_path(#post)
else
flash[:alert] = "Error creating new post!"
render :new
end
end
# Edit action retrives the post and renders the edit page
def edit
end
# Update action updates the post with the new information
def update
if #post.update_attributes(post_params)
flash[:notice] = "Successfully updated post!"
redirect_to post_path(#post)
else
flash[:alert] = "Error updating post!"
render :edit
end
end
# The show action renders the individual post after retrieving the the id
def show
end
# The destroy action removes the post permanently from the database
def destroy
if #post.destroy
flash[:notice] = "Successfully deleted post!"
redirect_to posts_path
else
flash[:alert] = "Error updating post!"
end
end
private
def post_params
params.require(:post).permit(:title, :body)
end
def find_post
#post = Post.find(params[:id])
end
end
Hopin
g to be able to create posts with body and title, and learn more about simple form.
Thanks in advance!
You wrote #post = Post.new without pass your parameters to your object, so when you save you object you save an empty object.
It should be either :
#post = Post.new(post_params)
Or directly
#post = Post.create(post_params)
Im making an application where an user can book a hour of training. I want to give the app the restriction of when an user has already booked one hour of training, it cant book more trainings, at least he deletes it or the book expires.
My code is:
Bookings controller:
Class BookingsController < ApplicationController
before_action :load_training, only: [:create]
def new
#booking = Booking.new
#training = Training.find(params[:training_id])
#booking.training_id
end
def create
#booking = #training.bookings.build(booking_params)
#booking.user = current_user
if #booking.save
flash[:success] = "Book done"
redirect_to trainings_path
else
render 'new'
end
end
def index
#bookings = Booking.where(training_id: params[:training_id])
end
def destroy
#booking = Booking.find(params[:id])
#booking.destroy
flash[:success] = "Book deleted"
redirect_to trainings_path
end
private
def booking_params
params.require(:booking).permit(:user_id, :training_id)
end
def load_training
#training = Training.find(params[:training_id])
end
end
Booking model:
class Booking < ApplicationRecord
belongs_to :user
belongs_to :training
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :training_id, presence: true
end
My routes.rb:
Rails.application.routes.draw do
root 'static_pages#home'
get '/signup', to: 'users#new'
get '/contact', to: 'static_pages#contact'
get '/about', to: 'static_pages#about'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :trainings do
resources :bookings
end
resources :users
end
Index of training view:
<h1>Hours</h1>
<ul class="trainings">
<% #trainings.each do |training| %>
<li>
<%= link_to training.hour, training_path(training) %>
</li>
<% end %>
</ul>
Show of training view:
<div class="row">
<section>
<h1>
HOUR: <%= #training.hour %>
</h1>
</section>
<section>
<h1>
SLOTS: <%= #training.slots %>
</h1>
</section>
<center>
<%= render 'bookings/booking_form' if logged_in? %>
<%= render 'bookings/index_bookings' if logged_in? %>
</center>
Booking_form.html.erb view:
<% unless current_user?(#user) %>
<% if current_user.is_booked(#training) %>
<%= link_to "Delete book", training_booking_path(#training), method: "delete", data: { confirm: 'Are you certain you want to delete this?' }, class: "btn btn-primary" %>
<% else %>
<%= link_to "Book", new_training_booking_path(#training), class: "btn btn-primary" %>
<% end %>
<% end %>
Im recieving the following error:
ActiveRecord::RecordNotFound in BookingsController#destroy
Couldn't find Booking with 'id'=1
Parameters:
{"_method"=>"delete",
"authenticity_token"=>"0uUXRwZdbhaKl16QxDi1HCM4H8IwEvGuoFOoxmkHhowoAUgZnlWPybck9DEbCKHh42SqXs3vtc01IRTqbx05wA==",
"training_id"=>"1", "id"=>"1"}
I would like to know why the method does not get the booking_id
When i try to see a training hour:
Started GET "/trainings/1" for 127.0.0.1 at 2017-03-11 01:03:23 -0400
Processing by TrainingsController#show as HTML
Parameters: {"id"=>"1"}
Training Load (0.1ms) SELECT "trainings".* FROM "trainings" WHERE "trainings"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendering trainings/show.html.erb within layouts/application
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered bookings/_booking_form.html.erb (2.3ms)
Rendered trainings/show.html.erb within layouts/application (4.0ms)
Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.2ms)
ActionView::Template::Error (No route matches {:action=>"show", :controller=>"bookings", :id=>nil, :training_id=>"1"} missing required keys: [:id]):
2: <% if current_user.not_booked(#training) %>
3: <%= link_to "Reservar", new_training_booking_path(#training), class: "btn btn-primary" %>
4: <% else %>
5: <%= link_to "Eliminar reserva", training_booking_path(#training, #booking), method: :delete,
6: data: { confirm: 'Are you certain you want to delete this?' }, class: "btn btn-primary" %>
7: <% end %>
8: <% end %>
Training model:
class Training < ApplicationRecord
has_many :users, through: :bookings
has_many :bookings
def can_book?
bookings.count < cantidad
end
end
Training controller:
class TrainingsController < ApplicationController
def show
#training = Training.find(params[:id])
end
def index
#trainings = Training.all
end
end
Thanks
In this line:
<%= link_to "Delete book", training_booking_path(#training), method: "delete", data: { confirm: 'Are you certain you want to delete this?' }, class: "btn btn-primary" %>
I think the path training_booking_path(#training) should also contain the #booking instance variable because of the nested routes.
So it should be training_booking_path(#training, #booking), method: :delete, etc.
You'd have to have #booking available in your view where the form shows up
I would use rake routes in your console to confirm the correct path and which resource ids need to be passed in
EDIT:
your trainings controller show action needs to have bookings available as an instance variable:
def show
#training = Training.find(params[:id])
#bookings = #training.bookings
end
Then in your training show view where the form resides, you need to loop over the #bookings and include an individual delete link for each:
<% #bookings.each do |booking| %>
<%= link_to "Delete book", training_booking_path(booking.training, booking), method: :delete, data: { confirm: 'Are you certain you want to delete this?' }, class: "btn btn-primary" %>
<% end %>
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.
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.
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.