devise (4.4.0)
Rails 5.1.4
I'm seeing this question asked a lot, but not finding the answer that works for me. I am showing that I am signing up and logging in, but current user set to nil. I'm thinking maybe it is the cookies, but I'm having a hard time parsing exactly how to fix that. One solution suggested adding
Rails.application.config.session_store :cookie_store, key: '_bejoy_session', domain: :all
to the config > session_store.rb which I did not have, but created and included. I'm just not sure what I'm missing here.
application controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
helper_method :current_user
helper_method :admin
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
end
end
def authorize
if !current_user
flash[:alert] = "You aren't authorized to visit that page."
redirect_to '/'
end
end
def admin_authorize
if !current_user || current_user.admin == false
flash[:alert] = "Only administrators can visit that page."
redirect_to new_user_session_path
end
end
def admin
current_user && current_user.admin
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :admin, :email])
end
end
routes.rb
Rails.application.routes.draw do
root :to => 'contents#index'
resources :contents
resources :visitors
devise_for :users, controllers: {
sessions: 'users/sessions',
passwords: 'users/passwords',
registrations: 'users/registrations'
}
end
Terminal:
Started POST "/users/sign_in" for 127.0.0.1 at 2018-01-07 12:31:25 -0800
Processing by Users::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6a0yiBCkmEN0W68xN/lVZH71YhT5i5tMEkFFYqnoIvMU0NJjH3LM3hPG+8yO3D1tXskh9pSA+PRFVKDmiKzN6A==", "user"=>{"email"=>"test#tester.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (1.9ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["email", "test#tester.com"], ["LIMIT", 1]]
(0.1ms) BEGIN
SQL (2.0ms) UPDATE "users" SET "current_sign_in_at" = $1, "last_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5 [["current_sign_in_at", "2018-01-07 20:31:26.091228"], ["last_sign_in_at", "2018-01-07 20:29:10.402839"], ["sign_in_count", 5], ["updated_at", "2018-01-07 20:31:26.092407"], ["id", 2]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 152ms (ActiveRecord: 4.5ms)
Started GET "/" for 127.0.0.1 at 2018-01-07 12:31:26 -0800
Processing by ContentsController#index as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
**current_user :nil
session id request :353a5e1d2bd295e8ac665e22e8f31314
user_signed_in? :false**
Rendering contents/index.html.erb within layouts/application
Content Load (0.2ms) SELECT "contents".* FROM "contents"
Rendered contents/index.html.erb within layouts/application (1.5ms)
Rendered partials/_author_photo_contact_block.html.erb (0.4ms)
Completed 200 OK in 53ms (Views: 49.1ms | ActiveRecord: 0.5ms)
contents controller:
class ContentsController < ApplicationController
before_action :authenticate_user!
# before_action :set_content, only: [:show, :edit, :update, :destroy]
def index
#contents = Content.all
logger.debug "current_user :#{current_user.inspect}"
logger.debug "session id request :#{request.session_options[:id]}"
logger.debug "user_signed_in? :#{user_signed_in?}"
end
def show
end
def new
#content = Content.new
end
def edit
end
def create
#content = Content.new(content_params)
respond_to do |format|
if #content.save
format.html { redirect_to #content, notice: 'Content was successfully created.' }
format.json { render :show, status: :created, location: #content }
else
format.html { render :new }
format.json { render json: #content.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #content.update(content_params)
format.html { redirect_to #content, notice: 'Content was successfully updated.' }
format.json { render :show, status: :ok, location: #content }
else
format.html { render :edit }
format.json { render json: #content.errors, status: :unprocessable_entity }
end
end
end
def destroy
#content.destroy
respond_to do |format|
format.html { redirect_to contents_url, notice: 'Content was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_content
#content = Content.find(params[:id])
end
def content_params
params.require(:content).permit(:main_image, :sidebar_image, :content, :sidebar)
end
end
Solution:
my current_user method in the application controller was overriding devise's own current_user method. I removed the current_user method I had in my application controller and it now shows:
current_user :#<User id: 2, email: "test#tester.com", username: "", admin: false, created_at: "2018-01-07 20:09:17", updated_at: "2018-01-07 21:33:51">
session id request :all
user_signed_in? :true
current user present? :true
found answer here: devise - can't display sign in or sign out in rails view
Related
I'm trying to save updates made in the inline tinymce editor in my rails app, but I don't know how to do it exactly as I want. I want the inline editor to be able to save while the view is 'html_safe'. I can save it fine if the form area is a text area (i.e. <div class="editor"><%= form.text_area :content %></div>), but I want to have the view in inline editor format so you can see your changes on the fly.
In the logs, it looks like the invitation params are closing before it's including the changes needed. How do I do this so that the inline editor changes are saved correctly?
Note: Everything else is working correctly, except the changes to the <%= #invitation.content %> are not being saved.
View:
<%= form_with(model: #invitation, local: true) do |form| %>
<%= form.hidden_field :event_id, value: #event.id %>
<div class="editor"><%= #invitation.content.html_safe %></div>
<script type="text/javascript">
tinyMCE.init({
selector: '.editor',
menubar: false,
inline: true,
plugins: "save",
toolbar: "save"
});
</script>
<% end %>
And my output from the log is:
Processing by InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2ssewH/CSN7is0P2LVrMkEmwZXcgmQqjWTjgrE6gGqAEv4dmLXFjEuOFJ9TRia+JF59SB6kKu5Le1xvt/FoxPg==", "invitation"=>{"event_id"=>"29"}, "mce_0"=>"<h1>Second Test Event CHANGEHERE!</h1>\r\n<h2>09/02/18 # 04:20</h2>\r\n<p> </p>\r\n<hr />\r\n<p>Bring Cheese</p>", "commit"=>"Update Invitation", "id"=>"7"}
Invitation Load (2.6ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT $2 [["id", 7], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:66
(0.3ms) BEGIN
↳ app/controllers/invitations_controller.rb:43
Event Load (1.8ms) SELECT "events".* FROM "events" WHERE "events"."id" = $1 LIMIT $2 [["id", 29], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:43
(0.3ms) COMMIT
↳ app/controllers/invitations_controller.rb:43
Redirected to http://localhost:3000/events/29
And my controller is a basic object controller:
class InvitationsController < ApplicationController
before_action :set_invitation, only: [:show, :edit, :update, :destroy]
# GET /invitations
# GET /invitations.json
def index
#invitations = Invitation.all
end
# GET /invitations/1
# GET /invitations/1.json
def show
end
# GET /invitations/new
def new
#invitation = Invitation.new
end
# GET /invitations/1/edit
def edit
end
# POST /invitations
# POST /invitations.json
def create
#invitation = Invitation.new(invitation_params)
respond_to do |format|
if #invitation.save
format.html { redirect_to #invitation, notice: 'Invitation was successfully created.' }
format.json { render :show, status: :created, location: #invitation }
else
format.html { render :new }
format.json { render json: #invitation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /invitations/1
# PATCH/PUT /invitations/1.json
def update
respond_to do |format|
if #invitation.update(invitation_params)
format.html { redirect_to #invitation.event, notice: 'Invitation was successfully updated.' }
format.json { render :show, status: :ok, location: #invitation }
else
format.html { render :edit }
format.json { render json: #invitation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /invitations/1
# DELETE /invitations/1.json
def destroy
#invitation.destroy
respond_to do |format|
format.html { redirect_to invitations_url, notice: 'Invitation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_invitation
#invitation = Invitation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def invitation_params
params.require(:invitation).permit(:name, :content, :event_id)
end
end
I am creating my first application in Rails, an e-commerce and would like to associate comments to the products, I created all the necessary structure, I have the user model, the products and the comments, I think I did everything right but when I go to render the form to insert the comment I get this error:
First argument in form can not contain nil or be empty
else
object = record.is_a?(Array) ? record.last : record
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
object_name = options[:as] || model_name_from_record_or_class(object).param_key
apply_form_for_options!(record, object, options)
end
the view that renders the form is this
<%= form_for(#comment, html: {multipart: true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new comment..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<span class="picture">
<%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
</span>
<% end %>
<script type="text/javascript">
$('#comment_picture').bind('change', function() {
size_in_megabytes = this.files[0].size/1024/1024;
if (size_in_megabytes > 8) {
alert('Maximum file size is 8MB. Please choose a smaller file.');
}
});
Comments Controller
class CommentsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy, :show]
before_action :correct_user, only: :destroy
def show
#comment = Comment.find(params[:id])
end
def create
#comment = current_user.comment.build(comment_params)
if #comment.save
flash[:success] = "Comment created!"
redirect_to store_url
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
#comment.destroy
flash[:success] = "Comment deleted"
redirect_to request.referrer || store_url
end
private
def comment_params
params.require(:comment).permit(:content, :picture)
end
def correct_user
#comment = current_user.comments.find_by(id: params[:id])
redirect_to store_url if #comment.nil?
end
end
Show of Product Controller
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
#products = Product.paginate(page: params[:page])
end
# GET /products/1
# GET /products/1.json
def show
#product = Product.find(params[:id])
#comments = current_user.comments.build if logged_in?
#comments = #product.comments.paginate(page: params[:page])
#rating = Rating.where(product_id: #product.id, user_id: #current_user.id).first
unless #rating
#rating = Rating.create(product_id: #product.id, user_id: #current_user.id, score: 0)
end
end
User Controller
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.where(activated: true).paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
#comments = #user.comments.paginate(page: params[:page])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to store_url
else
render 'new'
end
end
def update
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
def edit
#user = User.find(params[:id])
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Confirms the correct user.
def correct_user
#user = User.find(params[:id])
redirect_to(store_url) unless current_user?(#user)
end
# Confirms an admin user.
def admin_user
redirect_to(store_url) unless current_user.admin?
end
end
I can post you also believe the models if necessary, thanks to all who help me.
Log file:
Started GET "/en/products/4" for 127.0.0.1 at 2015-07-12 20:30:01 +0200
Processing by ProductsController#show as HTML
Parameters: {"locale"=>"en", "id"=>"4"}
Product Load (0.2ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", 4]]
CACHE (0.0ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", "4"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Rating Load (0.2ms) SELECT "ratings".* FROM "ratings" WHERE "ratings"."product_id" = ? AND "ratings"."user_id" = ? ORDER BY "ratings"."id" ASC LIMIT 1 [["product_id", 4], ["user_id", 1]]
(0.2ms) SELECT COUNT(*) FROM "ratings" WHERE "ratings"."product_id" = ? [["product_id", 4]]
(0.2ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."user_id" = ? [["user_id", 1]]
Rendered shared/_user_info.html.erb (3.0ms)
Rendered shared/_error_messages.html.erb (0.1ms)
(0.2ms) SELECT SUM("ratings"."score") FROM "ratings" WHERE "ratings"."product_id" = ? [["product_id", 4]]
CACHE (0.0ms) SELECT COUNT(*) FROM "ratings" WHERE "ratings"."product_id" = ? [["product_id", 4]]
Rendered shared/_comment_form.html.erb (7.6ms)
CACHE (0.0ms) SELECT SUM("ratings"."score") FROM "ratings" WHERE "ratings"."product_id" = ? [["product_id", 4]]
CACHE (0.0ms) SELECT COUNT(*) FROM "ratings" WHERE "ratings"."product_id" = ? [["product_id", 4]]
Rendered products/show.html.erb within layouts/application (24.3ms)
Rendered layouts/_header.html.erb (5.9ms)
Rendered layouts/_footer.html.erb (1.1ms)
Completed 200 OK in 205ms (Views: 197.7ms | ActiveRecord: 1.1ms)
Started POST "/comments?locale=en" for 127.0.0.1 at 2015-07-12 20:30:11 +0200
Processing by StaticPagesController#home as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"1sIh3jNERiiitmbyHQaQpAomMIgjXKkBVA/RqsIYDhYkD73gFOeMKyYYtmjSr9mu0ngyKSephYmfJhvvlKMigg==", "comment"=>{"content"=>"Hello! "}, "commit"=>"Post", "locale"=>"comments"}
comments translation not available
Rendered static_pages/home.html.erb within layouts/application (70.2ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Rendered layouts/_header.html.erb (4.4ms)
Rendered layouts/_footer.html.erb (0.6ms)
Completed 200 OK in 249ms (Views: 246.7ms | ActiveRecord: 0.2ms)
I've read this question : has_and_belongs_to_many, avoiding dupes in the join table but I wasn't able to fix my issue;
I've got a class TypeProduit which has many ExtensionFichier :
class TypeProduit < ActiveRecord::Base
has_and_belongs_to_many :extension_fichiers
end
and:
class ExtensionFichier < ActiveRecord::Base
has_and_belongs_to_many :type_produits
end
They are related thanks to
class LinkExtensionFichiers < ActiveRecord::Migration
def change
create_join_table :extension_fichiers, :type_produits
end
end
Edit:
Here's the [correct] Controler:
class TypeProduitsController < ApplicationController
before_action :set_type_produit, only: [:show, :edit, :update, :destroy]
# GET /type_produits
# GET /type_produits.json
def index
#type_produits = TypeProduit.all
end
# GET /type_produits/1
# GET /type_produits/1.json
def show
end
# GET /type_produits/new
def new
#type_produit = TypeProduit.new
end
# GET /type_produits/1/edit
def edit
end
# POST /type_produits
# POST /type_produits.json
def create
#type_produit = TypeProduit.new(type_produit_params)
puts "------extension_fichier_params------"
puts extension_fichier_params
##type_produit.extension_fichier_ids = extension_fichier_params
#type_produit.extension_fichiers << ExtensionFichier.find_by(:id => extension_fichier_params)
respond_to do |format|
if #type_produit.save
format.html { redirect_to #type_produit, notice: 'Type produit was successfully created.' }
format.json { render :show, status: :created, location: #type_produit }
else
format.html { render :new }
format.json { render json: #type_produit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /type_produits/1
# PATCH/PUT /type_produits/1.json
def update
respond_to do |format|
if #type_produit.update(type_produit_params)
format.html { redirect_to #type_produit, notice: 'Type produit was successfully updated.' }
format.json { render :show, status: :ok, location: #type_produit }
else
format.html { render :edit }
format.json { render json: #type_produit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /type_produits/1
# DELETE /type_produits/1.json
def destroy
#type_produit.destroy
respond_to do |format|
format.html { redirect_to type_produits_url, notice: 'Type produit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_type_produit
#type_produit = TypeProduit.find(params[:id])
end
def extension_fichier_params
#type_produit.extension_fichier_ids
end
# Never trust parameters from the scary internet, only allow the white list through.
def type_produit_params
params.require(:type_produit).permit(:nom, :extension_fichier_ids => [])
end
end
And here's the Rails server output:
Started POST "/type_produits" for 127.0.0.1 at 2015-01-27 17:55:15 +0100
Processing by TypeProduitsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4LBhwTvGjXOq+3qzO+loGUV/oBCYjW66aVDeE1Zj/AM=", "type_produit"=>{"nom"=>"qsdfqsdf", "extension_fichier_ids"=>["1", "2", ""]}, "commit"=>"Create Type produit"}
ExtensionFichier Load (0.4ms) SELECT "extension_fichiers".* FROM "extension_fichiers" WHERE "extension_fichiers"."id" IN (1, 2)
------extension_fichier_params------
1
2
ExtensionFichier Load (0.2ms) SELECT "extension_fichiers".* FROM "extension_fichiers" WHERE "extension_fichiers"."id" IN (1, 2) LIMIT 1
(0.1ms) begin transaction
TypeProduit Exists (0.1ms) SELECT 1 AS one FROM "type_produits" WHERE "type_produits"."nom" = 'qsdfqsdf' LIMIT 1
SQL (0.4ms) INSERT INTO "type_produits" ("created_at", "nom", "updated_at") VALUES (?, ?, ?) [["created_at", "2015-01-27 16:55:15.923132"], ["nom", "qsdfqsdf"], ["updated_at", "2015-01-27 16:55:15.923132"]]
SQL (0.1ms) INSERT INTO "extension_fichiers_type_produits" ("extension_fichier_id", "type_produit_id") VALUES (?, ?) [["extension_fichier_id", 1], ["type_produit_id", 8]]
SQL (0.1ms) INSERT INTO "extension_fichiers_type_produits" ("extension_fichier_id", "type_produit_id") VALUES (?, ?) [["extension_fichier_id", 2], ["type_produit_id", 8]]
SQL (0.0ms) INSERT INTO "extension_fichiers_type_produits" ("extension_fichier_id", "type_produit_id") VALUES (?, ?) [["extension_fichier_id", 1], ["type_produit_id", 8]]
(0.5ms) commit transaction
Why is rails making 3 insert while it just has 2 objects
There's a very obvious error in your controller code. Let's go step by step through your create action.
You create a new TypeProduit from type_produit_params which includes :nom and :extension_fichier_ids. You then output the value of extension_fichier_params which itself is #type_produit.extension_fichier_ids and you get "1\n2\n" so your #type_produit already has both of those extension_fichiers attached to it.
You then append ExtensionFichier.find_by(:id => extension_fichier_params) to #type_produit.extension_fichier_ids. Now a find_by is basically a where().first so it gets only the first one, ie. id=1. So now in your #type_produit.extension_fichiers array you have ids 1, 2 and 1 again. Ie. three objects.
Then you save the TypeProduit and all three of those associations are saved with the three INSERTs.
And yeah, the overall solution to this (other than fixing your unnecessary << code or your model-or-view that's adding 1 and 2) is to add the -> { uniq } scope to your habtm association(s) as per https://stackoverflow.com/a/20226630/152786
Have you tried the solution suggested by using-uniq-in-a-has-and-belongs-to-many-relationship-in-rails-4 (and maybe also adding an index as suggested in has-and-belongs-to-many-avoiding-dupes-in-the-join-table ?)
Calling redirect_to controller: 'messages', action: 'index' in one controller.
With index being defined in the messages controller as such:
def index
respond_to do |format|
format.json { render :json => Message.all }
format.html { }
end
end
However nothing seems to be redirected at the browser level, i.e. the /messages is not displayed.
Thoughts?
From the log:
Started POST "/users" for 127.0.0.1 at 2014-12-21 21:15:31 -0500
Processing by UsersController#create as */*
Parameters: {"name"=>"testsg", "phone_number"=>"8593385412"}
[1m[36m (4.0ms)[0m [1mBEGIN[0m
[1m[35mUser Exists (15.6ms)[0m SELECT 1 AS one FROM "users" WHERE "users"."handle" = 'testsg' LIMIT 1
[1m[36mUser Exists (0.0ms)[0m [1mSELECT 1 AS one FROM "users" WHERE "users"."phone_number" = '18593385412' LIMIT 1[0m
[1m[35mSQL (15.6ms)[0m INSERT INTO "users" ("created_at", "handle", "phone_number", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Mon, 22 Dec 2014 02:15:31 UTC +00:00], ["handle", "testsg"], ["phone_number", "18593385412"], ["updated_at", Mon, 22 Dec 2014 02:15:31 UTC +00:00]]
[1m[36m (31.3ms)[0m [1mCOMMIT[0m
Redirected to http://localhost:3000/messages
Completed 302 Found in 120ms (ActiveRecord: 68.0ms)
rest of controller code:
class MessagesController < ApplicationController
before_action :subscribe, :only => :index
# put your own credentials here
account_sid = 'XXXXXXXXXX'
auth_token = 'XXXXXXXXXX'
# set up a client to talk to the Twilio REST API
##client = Twilio::REST::Client.new account_sid, auth_token
def index
respond_to do |format|
format.json { render :json => Message.all }
format.html { }
end
end
def create
params.has_key?(:Body) ? message = params[:Body] : message = params[:message]
##client.messages.create(
from: 'XXXXXXXXXX',
to: 'XXXXXXXXXX',
body: "#{current_user.handle}: #{message}"
)
render :json => $pubnub.publish(
:channel => 'pubnub_chat',
:callback => lambda {|x|},
:message => {
#:user_id => current_user.id,
:user_id => current_user.id,
:message => "#{message}"
}
)
end
private
def subscribe
puts 'subscribing...'
$pubnub.subscribe(
:channel => 'pubnub_chat',
:callback => $callback
) unless $pubnub.subscription_running?
end
end
Where the redirect is coming from:
def create
#user = User.new(handle: params['name'], phone_number: params['phone_number'])
if #user.save
#render :json => [ #photo.to_jq_upload].to_json
session[:user_id] = #user.id
redirect_to controller: 'messages', action: 'index'
else
#render :json => [{ :error => "An error was encountered while processing your photos. Please try again." }], :status => 304
end
end
You have used redirect_to action: "course_page1", format: "html" and
return which is not right. Redirection will work fine if it was an
html request but not ajax. So if you want to redirect despite the fact
that the request was an ajax, use may something like this
format.js { render :js => "window.location.href =
'#{course_page_path}'" }
Rails console shows view is rendered, but doesn't render in browser
I use polymorphic associations with comments. When I try to add 'edit' and also 'destroy' in show template, I get the error in the title (just edit for now). How do I add both links to show?
comments_controller.rb
class CommentsController < ApplicationController
....
before_action :signed_in_user, only: [:new, :edit]
before_filter :load_commentable
def index
#commentable = load_commentable
#comments = #commentable.comments
end
def show
end
def edit
#commentable = load_commentable
end
def new
#commentable = load_commentable
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(comment_params)
#comment.user = current_user
if #comment.save
redirect_to #comment, notice: "Created."
else
render :new
end
end
def update
#comment = #commentable.comments.build(comment_params)
#comment.user = current_user
respond_to do |format|
if #comment.update(comment_params)
format.html { redirect_to #comment, notice: 'It was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
#commentable = resource.singularize.classify.constantize.find(id)
end
....
end
show.html.erb template
<%= link_to "Edit", [:edit, #commentable, :comment] %>
form
<%= form_for [#commentable, #comment] do |f| %>
....
full trace
log
Processing by CommentsController#show as HTML
Parameters: {"post_id"=>"1", "id"=>"2"}
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE
"comments"."id" = ? LIMIT 1 [["id", "2"]]
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" =
? LIMIT 1 [["id", "1"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" =
? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
(0.2ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."user_id" =
? [["user_id", 2]] CACHE (0.0ms) SELECT COUNT(*) FROM "comments"
WHERE "comments"."user_id" = ? [["user_id", 2]]
Rendered comments/show.html.erb within layouts/application (10.7ms)
Completed 500 Internal Server Error in 19ms
ActionView::Template::Error (No route matches {:action=>"edit",
:controller=>"comments", :post_id=>#, :id=>nil,
:format=>nil} missing required keys: [:id]):
25: <div class="thumbsdown"><%= link_to image_tag('othericons/thumbiconDown.PNG', height: '20', width: '20'),
"#" %>
26: <%= link_to image_tag('othericons/flagicon.PNG', height: '20', width: '18'), "#"
%>
27:
28: <%= link_to "Edit", [:edit, #commentable, :comment] %> 29:
30:
31: app/views/comments/show.html.erb:28:in
`_app_views_comments_show_html_erb___2937579164590753686_69833853514120'
Rendered /home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb
(1.6ms) Rendered
/home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(1.2ms) Rendered
/home/action/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb
within rescues/layout (19.1ms)
routes:
resources :posts do
resources :comments
end
Change the Edit Link as below:
<%= link_to "Edit", edit_post_comment_path(#commentable, #comment) %>
You have setup Post and Comment as nested routes, so you need to pass objects of Post as well as Comment to the edit path.
EDIT
For Polymorphic association, you could use it as below:
<%= link_to "Edit", [:edit, #commentable, #comment] %>