I am using Ruby: 3.1.0 and Rails: 7.0.4, I have added some abilities in ability.rb file for post permissions, getting warden proxy error.
app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
can :update, Post do |post|
post.user_id == user.id if user.present?
end
can :destroy, Post do |post|
post.user_id == user.id if user.present?
end
end
end
app/views/posts/index.html.erb
<h1 class="text-center m-4 text-success">Posts</h1>
<div id="posts">
<div class="row">
<% #posts.each do |post| %>
<%= render post %>
<% end %>
</div>
</div>
app/views/posts/_post.html.erb
<div class="col-lg-4 mb-2">
<div class="card border-0" style="width: 18rem;">
<% if post.image.present? && !post.image.image_url.file.nil? %>
<%= image_tag(post.image.image_url.url,size: "100x150",class: "card-img-top") %>
<% end %>
<span><%= postTimeAtCreated(post) %>
ago
<% if can? :update, post %>
<span style="margin-left:8px;">
<%= link_to "edit", edit_post_path(post) %>
</span>
<% end %>
<% if can? :destroy, post %>
<span style="margin-left:8px;">
<%= link_to "delete", post_path(post), data: { turbo_method: :delete } %>
</span>
<% end %>
</span>
<div class="card-body">
<p>
<span class="like">
<%= link_to fa_icon("thumbs-up"),"#", data: { action: "click->like#like", id: "post_#{post.id}", user_id: "user_#{post.user_id}" } %></span>
<span class="comment">
<%= link_to fa_icon("comment"),"#", data: { action: "click->like#comment",comment_url: new_post_comment_path(post.id) } %>
</span>
</p>
<p id="likes_<%= post.id %>"><%= like_counts(post.id) %>
likes
</p>
<h5 class="card-title"><%= post.title %></h5>
<p class="card-text"><%= post.description %></p>
</div>
</div>
</div>
app/controllers/posts_controller.rb
def create
#post = Post.new(post_params)
#post.user_id = current_user.id
#post.build_image if params[:post][:image_attributes] == nil
respond_to do |format|
if #post.save
format.html { redirect_to posts_url, notice: I18n.t("postCreate") }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
private
def post_params
params.require(:post).permit(:title, :description, image_attributes:
[:id,:image_url])
end
it's giving the below error in create action.
Devise could not find the Warden::Proxy instance on your request environment.
Make sure that your application is loading Devise and Warden as expected and that the Warden::Manager middleware is present in your middleware stack.
If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the Devise::Test::ControllerHelpers module to inject the request.env['warden'] object for you.
thanks!
Related
I need to get the value after it is created, just below the section "NEW"
Below is the image I intended to do, and after the data was created I wanted it right there
phrases_term_controller.rb
class PhrasesTermsController < ApplicationController
before_action :authenticate_user!
before_action :set_term
def new
#phrases_term = PhrasesTerm.new
end
def create
#phrases_term = #term.phrases_terms.new(phrases_term_params)
if #phrases_term.save
redirect_to term_phrases_term_path(#term, #phrases_term), notice: "Phrases_Term was successfully created"
else
render "new"
end
end
def show
#phrases_term = PhrasesTerm.find(params[:id])
end
private
def phrases_term_params
params.require(:phrases_term).permit(:term_id, :phrase_id)
end
def set_term
#term = Term.find(params[:term_id])
end
end
View
phrases_term
new.html.erb
<h1><%= I18n.t("pages.phrases_term.new.title") %></h1>
<%= render 'form', phrases_term: #phrases_term %>
_form.html.erb
<%= form_with scope: :phrases_term, url: term_phrases_terms_path, local: true do |form| %>
<% if phrases_term.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(phrases_term.errors.count, "error") %> prohibited this phrase from being saved:</h2>
<ul>
<% phrases_term.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :term_id %> :
<%= form.number_field :id %>
</div>
<div class="dropdown">
<button class="dropbtn">Phrase</button>
<div class="dropdown-content">
<a><%= form.select :phrase_id, Phrase.all.collect { |p| [ p.id ] }, include_blank: true %></a>
</div>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Term:
_form.html.erb
<%= form_with(model: term, local: true) do |form| %>
<% if term.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(term.errors.count, "error") %> prohibited this term from being saved:</h2>
<ul>
<% term.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :word %>
<%= form.text_field :word %>
</div>
<div class="field">
<%= form.label :meaning %>
<%= form.text_field :meaning %>
</div>
<div class="field">
<%= form.label :reading %>
<%= form.text_field :reading %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
I am not sure I have provided all the necessary information, if I want to add some more information, please comment below. ---Thank You.----
In my rails app I have a customer form of two steps.In step one customer enters his details and logo and pdf and in the next step he selects a theme which he like.
my customers_controller
def new
if current_user.admin?
#customer = Customer.new
#customer.additional_fields.build
else
redirect_to root_path, notice: 'You dont have admin permissions'
end
end
def edit
if current_user.admin?
#customer = Customer.find(params[:id])
else
redirect_to root_path, notice: 'You dont have admin permissions'
end
end
def theme_selector
#customer_id = params[:customer_id]
puts #customer_id
end
def create
Rails.logger.debug "PARAMS:"
params.each do |k,v|
Rails.logger.debug "#{k}: #{v}"
end
if current_user.admin?
#customer = Customer.new(customer_params)
respond_to do |format|
if #customer.save
format.html do
redirect_to #customer, notice: 'Customer was successfully created.'
end
format.json { render :show, status: :created, location: #customer }
else
format.html { render :new }
format.json do
render json: #customer.errors, status: :unprocessable_entity
end
end
end
else
redirect_to root_path, notice: 'You dont have admin permissions'
end
end
_form.html.erb
<%= form_for #customer, url: theme_selector_path,:method => :post,html: { multipart: true } do |f| %>
<input type="hidden" name="customer_id" value="<%= #customer.id %>">
<% if #customer.errors.any? %>
<div id="error_explanation">
<h2>
<%= "#{pluralize(#customer.errors.count, "error")} prohibited this customer from being saved:" %>
</h2>
<ul>
<% #customer.errors.full_messages.each do |msg| %>
<li>
<%= msg %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :address %>
<%= f.text_field :address, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :affiliate_id %>
<%= f.text_field :affiliate_id, class:"form-control" %>
</div>
<div class="control-group">
<%= f.label :logo, :class => 'control-label' %>
<div class="controls">
<%= f.file_field :logo,accept: 'image/png,image/gif,image/jpeg, image/jpg' %>
</div>
</div>
<div class="form-group">
<label>Upload File</label>
<%= f.file_field :file,accept: 'application/pdf' %>
</div>
<div class="form-group">
<% f.fields_for :additional_fields do | ing | %>
<%= ing.text_field :key, :size => 50 %>
<%= ing.text_field :value, :size => 50 %>
<% end %>
</div>
<div class="actions">
<div class="row">
<div class="col-md-5">
<span><%= f.submit 'Save', class: "btn-addmore" %></span>
<span><!--%= link_to 'Back', customers_path, class: "btn btn-danger" %--> </span>
</div>
<div class="col-md-2 col-md-offset-4">
<%= link_to "next", theme_selector_path, class: "btn-update" %>
</div>
</div>
</div>
<% end %>
I have a submit button at theme_selector.html.erb to create the customer.But I was getting an error "Paperclip::AdapterRegistry::NoHandlerError (No handler found for "#")" in customers controller create action.
development log:
Processing by CustomersController#create as HTML
Parameters: {"customer"=>{"name"=>"test", "address"=>"test", "affiliate_id"=>"test", "category"=>"", "domain"=>"test#web.com", "phone"=>"1111111111", "contact"=>"1214521", "email"=>"test#malibu.com", "comments"=>"none", "logo"=>"# <ActionDispatch::Http::UploadedFile:0x007f3f4946c258>", "file"=>"#<ActionDispatch::Http::UploadedFile:0x007f3f4946c208>"}}
PARAMS:
customer: #<ActionController::Parameters:0x007f3f442c0058>
controller: customers
action: create
Completed 500 Internal Server Error in 10ms (ActiveRecord: 1.0ms)
Paperclip::AdapterRegistry::NoHandlerError (No handler found for "# <ActionDispatch::Http::UploadedFile:0x007f3f4946c258>"):
app/controllers/customers_controller.rb:47:in `create'
Thanks in Advance!
The step-1 of customer form contains customer details and step-2 contains theme selection.However I was able to upload and save the data in step-1 but I was getting the error while saving the data from step-1 and step-2 together at the theme_selector page .
customer.rb
class Customer < ApplicationRecord
has_attached_file :logo
validates_attachment_content_type :logo, :content_type => /\Aimage\/.*\Z/
has_attached_file :file
validates_attachment_content_type :file, :content_type => "application/pdf"
end
I have a issue regarding update data using Rails 3.When user is editing profile and click on update button to update data,it could not update.I am explaining my codes below.
views/homes/userprofile.html.erb
<% if current_user %>
<div class="totaldiv">
<div class="navdiv"><span>STUDENT INFORMATION</span><span>Logged in as <%= current_user.email %></span></div>
<div class="wrapper">
<div id="leftsidebtn">
<ul>
<li>Book issue</li>
<li>Books Available</li>
<li>Magazines Purchase</li>
<li>Newspaper Purchase</li>
<li>Profile settings</li>
<li>My Blog</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="restdiv" id="ex3" >
<center>
<div class="edit-profile"><button type="button" class="btn btn-success" id="btnShowModal" >Edit Your Profile</button></div>
<div id="output"></div>
<div id="overlay" class="web_dialog_overlay"></div>
<div id="dialog" class="web_dialog">
<div class="edit-firstdiv">
<div class="web_dialog_title align_right">
Close
</div>
<%= form_for :users,:url => {:action => 'updatedata',:id => params[:id] } do |f| %>
<% if #users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#users.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #users.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="edit-firstname">
<label for="first_name">First Name</label>
<%= f.text_field :first_name,:id => 'first_name',:value => #users.first_name %>
</div>
<div class="edit-lastname">
<label for="last_name">Last Name</label>
<%= f.text_field :last_name,:id => 'first_name',:value => #users.last_name %>
</div>
<div class="edit-emailid">
<label for="emailid">Emailid</label>
<%= f.email_field :email,:id => 'first_name',:value => #users.email %>
</div>
<div class="edit-password">
<label for="password">Password</label>
<%= f.password_field :password,:id => 'first_name',:value => #users.password %>
</div>
<div class="edit-confirm">
<label for="Address">Password again</label>
<%= f.password_field :password_confirmation,:id => 'first_name' %>
</div>
<div class="edit-telephone">
<label for="phone">Phone no</label>
<%= f.telephone_field :tel_no,:id => 'first_name',:value => #users.tel_no %>
</div>
<div class="edit-address">
<label for="Address">Address</label>
<%= f.text_area :address,:class => 'address_text',:value => #users.address %>
<textarea id="first_name"></textarea>
</div>
<div class="edit-submit">
<%= f.submit 'Update Data',:class => 'btn btn-success' %>
</div>
</div>
<% end %>
</div>
</center>
</div>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
before_filter :authenticate_admin!,only: [:admin]
def index
end
def admin
end
def managebooks
#books=Book.new
if params[:id]
#books=Book.find(params[:id])
#book=Book.all
end
end
def savebooks
#books=Book.new(params[:books])
if #books.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'managebooks',:id => #books.id
else
flash[:notice]="Data couldnot submitted successfully"
flash[:color]="invalid"
render 'managebooks'
end
end
def remove
#books=Book.find(params[:id])
#books.destroy
end
def books
end
def showbooks
#books=Book.all
end
def searchbooks
#books=Book.all
end
def member
#users=User.new
end
def registration
#users=User.new
end
def savedata
#users=User.new(params[:users])
if #users.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data could not submitted successfully"
flash[:color]="invalid"
render 'registration'
end
end
def issuebooks
#issues=Issue.new
end
def savedissuebooks
#issues=Issue.new(params[:issues])
if #issues.save
flash[:notice]="information has saved successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data couldnot saved"
flash[:color]="invalid"
render 'issuebooks'
end
end
def availablebooks
#books=Book.all
end
def userissues
#issues=Issue.all
end
def magazine
#magazines=Magazine.new
end
def savemagazines
#users=User.find(params[:id])
#magazines=Magazine.new(params[:magazines])
#magazines.user_id=#users.id
if #magazines.save
flash[:notice]="Data submitted successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:notice]="Data could not saved"
flash[:color]="invalid"
render 'magazines'
end
end
def magazineissue
#magazines=Magazine.all
#users=User.find #magazines.first.user_id
end
def blog
#blogs=Blog.new
end
def savecomments
#users=User.find(params[:id])
#blogs=Blog.new(params[:blogs])
#blogs.user_id=#users.id
if #blogs.save
flash[:notice]="Comment has been posted successfully"
flash[:color]="valid"
redirect_to :action => "showcomment"
else
flash[:notice]="Comment could not saved"
flash[:color]="invalid"
render 'blog'
end
end
def showcomment
#blogs=Blog.all
end
def newspaper
#newspapers=Newspaper.new
end
def savenewspaper
#users=User.find(params[:id])
#newspapers=Newspaper.new(params[:newspapers])
#newspapers.user_id=#users.id
if #newspapers.save
flash[:notice]="newspaper data saved successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'newspaper'
end
end
def adminnewspaperissue
#newspapers=Newspaper.all
#users=User.find #newspapers.first.user_id
end
def userprofile
#users=User.find(params[:id])
end
def updatedata
#users=User.find(params[:id])
if #users.update_attributes(params[:users])
flash[:notice]="User Data has updated"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:alert]="Data could not updated"
flash[:color]="invalid"
render :action => 'userprofile'
end
end
end
From the above code the else part is executing inside updatedata action.Please help to resolve this issue.
I have a Rails 3.2.14 app where I have calls, calls have units, units have statuses, and calls times in the model such as in_service_time.
I'm trying to write a controller action called in_service which updates the unit's status to "In Service" and time stamps call.in_service_time to Time.zone.now and does all of this via put remote (Ajax).
What I've written so far seems to work by updating the unit status and time stamping the call.in_service_time. But using :remote => true doesn't render the partials as I've specified in the in_service action. I have to wait for the screen to refresh via a getScript call in my index.html.erb for the call status to update. If I use :remote => false it reloads the page immediately without problems. If I use the :remote => true I also throw an exception in my development.log for NihlClass.
Below are excerpts of the code in question, the full code can be found here to keep things easier to read: full code
index.html.erb
<div id="active">
<%= render "assigned_calls" %>
</div>
<div id="inactive">
<%= render "unassigned_calls" %>
</div>
<script>
$(function() {
setInterval(function(){
$.getScript("/calls").fail(function(jqxhr, settings, exception) {
window.location = "/users/sign_in?duplicate_session=true";
});
}, 10000);
});
</script>
index.js.erb
$("#active").html("<%= escape_javascript render("assigned_calls") %>");
$("#inactive").html("<%= escape_javascript render("unassigned_calls") %>");
routes.rb excerpt
resources :calls do
member do
post 'close'
post 'cancel'
post 'note'
get 'opencall'
get 'new_return'
get 'duplicate_call'
get 'edit_times'
put 'update_billing'
post 'dispatch_call'
put 'en_route'
put 'on_scene'
put 'to_hospital'
put 'at_hospital'
put 'in_service'
end
calls_controller.rb excerpt
def in_service
#call = Call.find(params[:id])
#unit = #call.units.first
#call.update_attributes(in_service_time: Time.zone.now)
#call.save
#unit.status = Status.find_by_unit_status("In Service")
#unit.save
respond_to do |format|
format.html { redirect_to calls_url }
format.js { render "index" }
end
end
_assigned_calls.html.erb
<div class="page-header">
<span class="badge badge-important"><%= #unassigned.count %></span> <strong>Unassigned calls</strong>
<span class="badge badge-info"><%= #assigned.count %></span> <strong>Active calls</strong>
<span class="badge badge-warning"><%= #scheduled.count %></span> <strong>Scheduled calls</strong>
<%= render "search" %>
<h2>Active Calls</h2>
</div>
<% #assigned.each do |call| %>
<div class="widget">
<div class="widget-header">
<div class="pull-right">
<%= link_to 'View', call, :class => 'btn btn-close'%>
<% if dispatch? %>
<%= link_to 'Edit', edit_call_path(call), :class => 'btn btn-close'%>
<%= link_to 'Close', close_call_path(call), confirm: 'Are you sure you want to close the call?', :method => :post, :class => 'btn btn-danger' %>
<%= link_to 'Cancel', cancel_call_path(call), confirm: 'Are you sure you want to cancel the call?', :method => :post, :class => 'btn btn-warning' %>
<% end %>
</div>
<i class="icon-phone"></i>
<h3><%= link_to call.incident_number, call %> <span><%= status(call) %></span></h3>
<% if call.traffic_type == "Emergency" %>
<span class="badge badge-important"><%= call.traffic_type %></span>
<% else %>
<span class="badge badge-info"><%= call.traffic_type %></span>
<% end %>
</div>
<div class="widget-content">
<div class="row">
<div class="span3">
<h4>Patient Name: <small><%= call.patient_name %></small></h4>
<div class="large-display">
<% if call.call_status == "open" %>
<div class="large <%= elapsed_overdue(call.elapsed_time) %>"><%= TimeFormatter.format_time(call.elapsed_time)%></div>
<div class="small">Elapsed Time</div>
<% else %>
<% if call.closed_at? %>
<div class="large <%= elapsed_overdue(call.run_time) %>"><%= TimeFormatter.format_time(call.run_time)%></div>
<div class="small">Run Time</div>
<% end %>
<% end %>
</div>
</div>
<div class="span2">
<address>
<strong><%= transferred_from(call) %></strong><br>
<%= transferred_from_address(call) %>
</address>
</div>
<div class="span1"><i class="icon-arrow-right dim"></i></div>
<div class="span2">
<address>
<strong><%= transferred_to(call) %></strong><br>
<%= transferred_to_address(call) %>
</address>
</div>
<div class="span3">
<% if call.service_level.level_of_service == "WC" %>
<div class="left-icon dim"><i class="icon-user"></i></div>
<% else %>
<div class="left-icon dim"><i class="icon-ambulance"></i></div>
<% end %>
Assigned to <strong>Unit <%= call.units.map(&:unit_name).join(", ") %></strong><br />
<% call.units.each do |unit| %>
<div class="<%= set_status(unit.status) %>"><%= unit_status(unit) %></div>
<% end %>
</div>
</div>
<hr />
<div class="row">
<div class="span2">
<div class="large-display">
<div class="medium <%= transfer_due(call.transfer_date) %>"><%= call.transfer_date.strftime("%m/%d/%y %H:%M") %></div>
<div class="small">Transfer Date</div>
</div>
</div>
<div class="span1">
<div class="large-display">
<div class="small"><%= call.nature.try(:determinant) %></div>
<div class="small">Nature</div>
</div>
</div>
<div class="span5">
<% if call.unit_ids.present? %>
<div class="large-display">
<div class="progress progress-striped"><%= progress_bar(call) %></div>
<div class="small"><%= call.units.first.status.unit_status %></div>
<div><%= link_to 'En Route', en_route_call_path(call), :class => 'btn btn-warning btn-medium', :method => :put, :remote => true %><%= link_to 'On Scene', on_scene_call_path(call), :class => 'btn btn-primary btn-medium', :method => :put, :remote => true %><%= link_to 'To Hospital', to_hospital_call_path(call), :class => 'btn btn-warning btn-medium', :method => :put, :remote => true %><%= link_to 'At Hospital', at_hospital_call_path(call), :class => 'btn btn-danger btn-medium', :method => :put, :remote => true %><%= link_to 'In Service', in_service_call_path(call), :class => 'btn btn-success btn-medium', :method => :put, :remote => true %></div>
<div>ER: <%= call.en_route_time.try(:strftime, "%m/%d/%y-%k:%M") %> OS: <%= call.on_scene_time.try(:strftime, "%m/%d/%y-%k:%M") %> TO: <%= call.to_hospital_time.try(:strftime, "%m/%d/%y-%k:%M") %> AT: <%= call.at_hospital_time.try(:strftime, "%m/%d/%y-%k:%M") %> IS: <%= call.in_service_time.try(:strftime, "%m/%d/%y-%k:%M") %></div>
</div>
<% end %>
</div>
<div class="span3">
<div class="left-icon dim"><i class="icon-user"></i></div>
<%= render partial: "medics_for_call", locals: {call: call} %>
</div>
</div>
</div>
</div>
<% end %>
development.log excerpt
NoMethodError - undefined method `count' for nil:NilClass:
app/views/calls/_assigned_calls.html.erb:2:in `_app_views_calls__assigned_calls_html_erb___2549181816739942207_70125964034780'
You're never setting #unassigned in your in_service action. So sending count to it throws an exception.
Rendering an action's view (render "index") from a different action does not execute the action's controller code.
EDIT: How to make it DRY:
class CallsController < ApplicationController
...
def index
setup_scheduling_variables
#units = Unit.order("unit_name")
#overdue = #assigned.select{|call| call.elapsed_time > 3600}
#inservice = Unit.in_service
end
def in_service
...
respond_to do |format|
format.html { redirect_to calls_url }
format.js do
setup_scheduling_variables
render "index"
end
end
end
private
def setup_scheduling_variables
#assigned = params[:search].present? ? Call.search(params[:search]) : Call.assigned_calls.until_end_of_day.order("transfer_date ASC")
#unassigned = Call.unassigned_calls.until_end_of_day
#scheduled = Call.scheduled_calls
end
In my ActionController I have the following:
format.html {
flash[:notice] = "Success"
redirect_to #event
}
However, I want to use a partial for the flash notice. I tried using render :partial but this gave me double render errors. Any ideas if this can be done?
Try using render_to_string This should let you render a partial a string without getting a double render error.
Flash messages partial code
<div class="container">
<div id="messages">
<div class="message-container">
<% flash.each_with_index do |(k,v),i| %>
<div id="message-<%= i %>" class="actual-message alert-<%= k.to_s.sub('_stay', '') %>">
<a class="close" data-dismiss="alert" style="float:right">x</a>
<% if v.is_a?(Array) %>
<ul>
<% v.each do |vv| %>
<li><%= vv %></li>
<% end %>
</ul>
<% else %>
<%= raw v %>
<% end %>
</div>
<% end %>
</div>
</div>
</div>
render in your application.html.erb using
"layouts/flash_messages" %>