how to disable submit button after being used 1 time - mysql

What I am trying to do is the following.
A user.rb can answer.rb several application.rb's created by a company.rb. However the user can only answer once per unique application.
I've already disabled this in the model but can't figure out how to do it in the view.
My answer controller:
class AnswersController < ApplicationController
before_action :authenticate_user!
def show
#application = Application.find(params[:id])
#answer = Answer.new
end
def create
#answer = Answer.new(answer_params.merge(:user_id => current_user.id))
if #answer.save
flash[:notice] = "You've successfully applied"
redirect_to root_url
else
flash[:alert] = "You've already applied"
redirect_to root_url
end
end
private
def answer_params
params.require(:answer).permit(:answer_1, :answer_2, :answer_3, :application_id)
end
end
in the answer model I have a user_id that is stored.
Now my thinking is that we look at the current answer :id and check if current_user.id is present in it, if so we disable the button. But I haven't been able to do anything that turned out successfully.
The show.html.erb looks like this:
<%= form_for #answer do |f| %>
<%= f.hidden_field :application_id, value: #application.id %>
<p>Question 1: <%= #application.question_1 %></p>
<%= f.text_area :answer_1 %>
.......
<%= f.submit "Submit" %>
<% end %>

If use of jQuery is possible in Ruby, you can use the .one() method
.one( events [, selector ] [, data ], handler ) [jQuery 1.7+]
events
Type: String
One or more space-separated event types and optional namespaces, such as "click"
or "keydown.myPlugin".
selector
Type: String
A selector string to filter the descendants of the selected elements that trigger
the event. If the selector is null or omitted, the event is always triggered when
it reaches the selected element.
data
Type: Anything
Data to be passed to the handler in event.data when an event is triggered.
handler
Type: Function( Event eventObject )
A function to execute when the event is triggered. The value false is also allowed as
a shorthand for a function that simply does return false.

Related

Nested object's form input not displaying any errors despite of nested_object.errors returning a hash with errors?

I have a Plan model that has_many Versions. I'm nesting Version inputs inside a Plan form, and even though the validations seem to be working, the form inputs don't display any errors.
I don't know if this is relevant, but because the nested inputs are scattered around the form, I open the nested input blocks with simple_fields_for :versions_attributes[0] instead of simple_fields_for :versions because I want to be specific that all the inputs around the form correspond to the same object. Otherwise the hash would be built with a different key for each different block (eg: versions_attributes: { 0: {amount: value}, 1: {another_field: another_value} } instead of versions_attributes: { 0: {amount: value, another_field: another_value}}.
plan.rb:
class Plan < ApplicationRecord
has_many :versions
accepts_nested_attributes_for :versions
validates_associated :versions
end
version.rb
class Version < ApplicationRecord
belongs_to :plan
validates :amount, presence: true
end
plans_controller.rb
class PlansController < ApplicationController
def new
#plan = current_account.plans.build
#version = #plan.versions.build
end
def create
#plan = current_account.plans.build(plan_params)
if #plan.save
redirect_to plan_path(#plan)
else
#plan = #base_plan.plans[0]
render :new
end
end
def plan_params
params[:plan][:versions_attributes]["0"]&.merge!(
account_id: current_account.id,
)
params.require(:plan).permit(
:name,
:short_description,
versions_attributes: %i[id account_id amount],
)
end
end
form.html.erb:
<%= simple_form_for [#plan] do |f| %>
<%= f.input :name %>
<%= f.input :short_description %>
<%= f.simple_fields_for "versions_attributes[0]" do |v| %>
<%= v.input :amount %>
<% end %>
<% end %>
Problem:
#version.errors contains a hash with the object's validation errors. However, the related inputs don't render validation errors nor are the form-group-invalid has-error CSS classes added (provided by the simple_form gem).
My first guess is that it's got something to do with the create action. My second guess is that it's got something to do with the way I'm opening the nested input's blocks (described above).
Either way, I'm confused because #version.errors contains the nested object's errors.

Getting a button to add current user's id to a field

I'm trying to get a simple button press that will store current user's id into a field but getting an error that says
ActionController::ParameterMissing (param is missing or the value is empty: request):
Here's my code.
The button code
<%= form_for(request.accept, remote: true) do |f| %>
<%= f.submit "Accept", class: "btn btn-primary" %>
<% end %>
request_controller
def accept
#request.ssp_id = current_user.id
#request.save
flash[:success] = "The request have been accepted!"
end
Thanks in advance.
The ParameterMissing error is probably because you have specified to require request model in your parameters through strong_params.
Since you are trying to update an existing record with the current_user you don't need a form.
Update your accept action in the RequestsController:
def accept
#request = Request.find params[:id]
if #request.update_attribute(:ssp, current_user)
redirect_to requests_path
flash[:success] = "The request have been accepted!"
end
end
Request model
class Request < ApplicationRecord
belongs_to :ssp, class_name: "User"
end
And your routes:
resources :requests do
member do
get "accept"
end
end
<%= link_to 'Accept request', accept_request_path(request) %>
Also as a recommendation try to use a different name for your model since the word request is wide use in Rails. I don't know if this could be a problem latter on.

update_all not updating my database

I have a many-to-many relationship between my reservation db and cars db, and the following is in my reservation controller and is routed to the post.
def reserveConfirm
pick_time = params[:pick_y].to_s+"-"+params[:pick_m].to_s+"-"+params[:pick_d].to_s+" "+"#{params[:pick_h]}:00:00"
return_time = params[:return_y].to_s+"-"+params[:return_m].to_s+"-"+params[:return_d].to_s+" "+"#{params[:return_h]}:00:00"
##reservation = Reservation.find(params[:id])
#car = Car.where(:id => params[:car_id]).update(:status => 'reserved')
#reservation = Reservation.new(status:'reserved',
pick_up_time: pick_time,
return_time: return_time,
user_id:current_user.id)
if #reservation.save
#flash[:success] = #reservation.id
flash[:success] = 'shit'
redirect_to(:action => 'history',:notice => 'Check out was successfully created.',:id =>current_user.id )
else
flash[:success] = 'success'
format.html { render action: "reserve" }
format.json { render json: #reservation.errors.full_messages, status: :unprocessable_entity }
end
end
things start to get confusing from here. In my reservation controller, every time i want params[:id], i am not getting the reservation id. I have my new reservation created and routed to get in action reserve. The [:id] seems to either be nil or a car_id, since the link i have is reservation/:id(:format), and this :id is somehow the cars id instead of my new reservation id. My reserve action does Reservation.new
def reserve
#reservation = Reservation.new
#car = Car.find(params[:car_id])
if #car == nil
flash[:danger] = "no car found"
else
flash[:danger] = #car.id
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: #reservation }
end
end
I am in the jungle and everything tangles up in the woods.
In reserve action, I can find car by car_id which is the reservation/:id filed, which is 2 here. But in my reserveConfirm, i am getting a nil #car object, which forces me to use where that finds all car with id , although only one cause the id is unique. And worse, after i get #car, i want to update its status to reserved, but when i look into db, it is not ever changed.
My form, which passes data is here:
<%= form_for #reservation,:url => { :action => "reserveConfirm" } do |f| %>
<%=f.label :Date%>
<%=f.date_select :pick_up_time %>
<%= f.hidden_field :car_id, :value=> #car.id %>
<%= f.hidden_field :user_id, :value=> current_user.id %>
<%= f.submit "Confirm", data: { confirm: 'Are you sure?', class: "btn btn-default" }%>
Hope someone can kindly help me with this, much appreciate!
First of all, you should verify if you are getting #car correctly.
I guess you are able to use 'byebug' . Try writing 'byebug' at beginning of reserveConfirm method.
def reserveConfirm
byebug
#your code
end
Using byebug, you can look your rails server (in terminal) and debug your code. Try writing 'params' to check all params that you are receiving. You can write 'exit' or 'continue' using byebug. (More info: Debugging using byebug)
If params[:car_id] exists, your code should be like:
#car = Car.find(params[:car_id])
#car.status = 'reserved'
if #car.update
#code
else
#code
end
Check that and tell me how it goes.

Ruby on Rails - Optional user message when they submit their vote to database

My app allows users to see a list of questions and allows them to vote for an option (uniquely). I have a users table, a questions table, an options table and an answers table.
I've created the migration to add the column message to the answers table and I can show the messages on the page, just need to actually send the message to the DB table - this is the button to allow the user to vote:
<%= link_to 'Vote', question_option_upvote_path(#question, option), data: { confirm: 'Are you sure you want to vote for this option?' }, :class => 'voteNow', method: :post %>
I'm struggling to hook up the textarea to be sent when the user clicks to vote, I'm using simply <%= text_area :message, autofocus: true %> to create my textarea on it's own. Do I need to setup a whole form for this or is there a simple way to pull the contents when the user votes? My options controller is:
class OptionsController < ApplicationController
def create
#question = Question.find(params[:question_id])
#option = #question.options.create(option_param)
redirect_to question_path(#question)
end
def upvote
#question = Question.find(params[:question_id])
#option = Option.find(params[:option_id])
Answer.create(user_id: current_user.id, question_id: #question.id, option_id: #option.id)
redirect_to question_path(#question)
end
private
def option_param
params.require(:option).permit(:option_text)
end
end
Let me know if I need to include anything else in this message!

Routing Error in Rails No route matches {:action=>"ticket_action", :controller=>"tickets"}

This is an error I can not seem to figure out I believe I have it routed. This is the error
No route matches {:action=>"ticket_action", :controller=>"tickets"}
I get this error after this code
<h4>New Action</h4>
<% form_tag :action => 'ticket_action' do %>
<p><b>Description</b><br/>
<%= text_area 'description', 'description', 'rows' => 5 %><br/>
User: <%= select("actUser", "user_id", User.find(:all).collect{|u| [u.name, u.id] } )%>
<% end %>
I have this on my ticket_controller.rb is that the proper placement for that
#action
def ticket_action
#act = Action.new(
"ticket_id" => flash[:ticket_id],
"description" => params[:description]['description'],
"user_id" => params[:actUser]['user_id']
)
routes
actions GET /actions(.:format) actions#index
POST /actions(.:format) actions#create
new_action GET /actions/new(.:format) actions#new
edit_action GET /actions/:id/edit(.:format) actions#edit
action GET /actions/:id(.:format) actions#show
PUT /actions/:id(.:format) actions#update
DELETE /actions/:id(.:format) actions#destroy
tickets GET /tickets(.:format) tickets#index
POST /tickets(.:format) tickets#create
new_ticket GET /tickets/new(.:format) tickets#new
edit_ticket GET /tickets/:id/edit(.:format) tickets#edit
ticket GET /tickets/:id(.:format) tickets#show
PUT /tickets/:id(.:format) tickets#update
DELETE /tickets/:id(.:format) tickets#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
clients GET /clients(.:format) clients#index
POST /clients(.:format) clients#create
new_client GET /clients/new(.:format) clients#new
edit_client GET /clients/:id/edit(.:format) clients#edit
client GET /clients/:id(.:format) clients#show
PUT /clients/:id(.:format) clients#update
DELETE /clients/:id(.:format) clients#destroy
It would be helpful to post the route to debug this problem, your route may refer to tickets yet your class is ticket.
You should look into restful routes, especially given your use case. It seems you should really have an actions controller (ActionsController, named controllers/actions_controller.rb) and then post to the create action and provide a restful route (resources :actions)
My suggestion would be to read up on rest and rails first.
Additionally the flash isn't where you should store your ticket_id, ideally you should retrieve it in your actions controller's create action by posting to /action/ticket_action/1 and retrieving the id by accessing params[:id] in the controller. If you really must, store it in the session (session[:ticket_id] = "1") but 'rest' is where you should be headed. The flash will be removed and should only be set in the controller and then displayed on the next page, it will be deleted thereafter.
Update: ok thanks for posting your routes.
You can add the missing route like this if you want:
resources :tickets do
member do
post 'ticket_action'
end
end
But it would be better to follow this pattern:
In actions controller:
def new
#action = Action.new
end
Your form should look a bit like this, Rails will know to post to actions#create because #action is a new record (you can check #action.new_record? if you want)
<%= form_for #action do |f| %>
<%= f.text_area :description, :rows => 5 %>
<%= f.hidden_field :ticket_id, flash[:ticket_id] %>
<%= f.select :user_id, User.find(:all).collect{|u| [u.name, u.id] } %>
<%= f.submit "Create" %>
<% end %>
Then in your actions controller:
def create
#action = Action.new(params[:action])
end
or with less magic:
def create
#action = Action.new(:user_id => params[:action][:user_id],
:description => params[:action][:description],
:ticket_id => params[:action][:ticket_id])
if #action.save
redirect_to actions_path(#action, :notice => "Created action")
else
render :new # any errors will be in #action.errors
end
end
You should really be setting the ticket_id in the actions controller's new method though.
def new
#action = Action.new(:ticket_id => params[:ticket_id])
end
And then in your form:
<%= f.hidden_field :ticket_id %>
Your file name should be "tickets_controller.rb", plural.