userid in params but unable use it in controller? - ruby-on-rails

this is my view file i am sending the userid in parameters,
<%= form_for :user, :url=>{:action=>'update'},:method=>"get",:html=>{:class=>'form-horizontal'} do |f|%>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Admin</label>
<div class="col-md-4">
<%= f.radio_button :is_admin, 'true', :checked => true %> Yes
<%= f.radio_button :is_admin, 'false' %> no
<%= f.hidden_field :userid, value: #id %>
</div>
</div>
<%= f.submit ('save') %>
<% end %>
but when i try to access it in my controller i get following error (record not found):
I am finding user in my controller method like this:
def update
#users = User.all
#uid = params[:userid]
#users = User.find_by_id!(#uid)
if #users.update_attributes(user_params)
flash[:notice] = "User updated successfully."
redirect_to :action=>'view'
else
flash[:notice] = "Error while updating user."
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:is_admin,:is_member)
end
end

Instead of:
#uid = params[:userid]
Try:
#uid = params[:user][:userid]

Related

incorrect url when send patch method in redmine plugin

My route :
patch '/projects/:project_id/budgets/:id', to: 'budgets#update', as:'patch_budget' #update
when i send a patch method to this route, :project_id should be my project_id, like:
/projects/test_project/budgets/14
but it turns to budget.id, like:
/projects/14/budgets/14
_form.html.erb
<%= form_with model: budget do |f| %>
<div>
<%= f.label :name, "預算名稱" %><br>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :description, "說明" %><br>
<%= f.text_field :description %>
</div>
<div>
<%= f.label :category, "預算類別" %><br>
<%= f.text_field :category %>
</div>
<div>
<%= f.label :quantity, "數量" %><br>
<%= f.text_field :quantity %>
</div>
<div>
<%= f.label :unit_cost, "單位成本" %><br>
<%= f.text_field :unit_cost %>
</div>
<div>
<%= f.label :issue_id, "議題" %><br>
<%= f.select(:issue_id, Issue.all.collect { |i| [ i.subject, i.id] }) %>
</div>
<div>
<%= f.submit "送出" %>
</div>
<% end %>
edit.html.erb
<h1>編輯預算</h1>
<%= render "form", budget: #budget %>
<br/>
<%= link_to "回預算列表", budgets_path %>
budgets_controller.rb
class BudgetsController < ApplicationController
before_action :find_project, :authorize
def index
#budgets = Budget.all
#sum = Budget.all.sum(:total_cost).round(1)
end
def new
#budgets = Budget.new
end
def create
#budgets = Budget.new(budget_params)
#budgets.project_id = #project.id
#budgets.total_cost = #budgets.quantity * #budgets.unit_cost
#budgets.created_by_id = User.current.id
if #budgets.save
redirect_to budgets_path, notice: "新增預算成功!"
else
render :new
end
end
def edit
#budget = Budget.find(params[:id])
end
def update
#budget = Budget.find(params[:id])
if #budget.update(budget_params)
redirect_to budgets_path, notice: "修改成功!"
else
render :edit
end
end
def destroy
#budget = Budget.find(params[:id])
#budget.destroy if #budget
redirect_to budgets_path, notice: "預算已刪除!"
end
def show
#budget = Budget.find(params[:id])
#create_by = User.find(#budget.created_by_id)
if #budget.modified_by_id != nil
#modified_by = User.find(#budget.modified_by_id)
end
end
private
def find_project
# #project variable must be set before calling the authorize filter
#project = Project.find(params[:project_id])
end
def budget_params
params.require(:budget).permit(:name, :description, :category,
:quantity, :unit_cost, :issue_id)
end
end
Create and delete are running normally, I try many ways in my form, but it didn't work, thanks for the help.
You need to pass an array to generate nested routes:
<%= render "form", budget: #budget, project: #project %>
<%= form_with model: [project, budget] do |f| %>
See https://api.rubyonrails.org/v7.0/classes/ActionDispatch/Routing/PolymorphicRoutes.html

Ruby on Rails form error not giving any output/ not working

Hello guys I searched everywhere on how to output form errors but no luck. I tried almost all the code I found on the internet but still didn't work.
Here are some of my files:
view/books/new.html.erb
<div class="container">
<h2>Create a new book</h2>
<%= form_with model: #book, url: create_new_book_path do |f| %>
<% if #book.errors.any? %>
<ul>
<% #book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="form-group row">
<%= label_tag(:title, "Title:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :title, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:price, "Price:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :price, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:subject_id, "Subject:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.collection_select :subject_id, #subjects, :id, :name, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:description, "Book description:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_area :description, class: "form-control" %>
</div>
</div>
<%= submit_tag "Create book", class: "btn btn-success" %>
<%= link_to "Cancel", books_path, class: "btn btn-danger" %>
<% end %>
<br/>
</div>
books_controller.rb
class BooksController < ApplicationController
def index
#books = Book.all
end
def show
#book = Book.find(params[:id])
end
def new
#book = Book.new
#subjects = Subject.all
end
def create
#book = Book.new(book_params)
end
def book_params
params.require(:book).permit(:title, :price, :subject_id, :description)
end
def edit
#book = Book.find(params[:id])
#subjects = Subject.all
end
def update
#book = Book.find(params[:id])
if #book.update_attributes(book_params)
redirect_to action: "index"
else
#subjects = Subject.all
render action: "edit"
end
end
def destroy
Book.find(params[:id]).destroy
redirect_to action: "index"
end
end
routes.rb
get 'books/new', to: 'books#new', as: 'new_book'
post 'books/create', to: 'books#create', as: 'create_new_book'
view/layouts/application.html.erb
<main role="main">
<%= yield %>
</main>
I don't really know what I'm missing to get the errors, grateful for your answers!!
try putting them in a flash like this and render it in your view
def create
#book = Book.new
if #book.update(book_params)
flash[:notice] = 'success'
redirect_to action: 'index'
else
flash[:alert] = #book.errors.full_messages.join(', ')
redirect_to action: 'index'
end
end
and in your view render those flashes like
<% if flash[:notice]%>
<span class='notice'><%= flash[:notice] %></span>
<% end %>
<% if flash[:alert]%>
<span class='alert'><%= flash[:alert] %></span>
<% end %>

Signup form for admin in rails

I have a parent table and in it there is a boolean field admin. I have a admin signup page where i want a hidden field for admin to set as true. Please help. I have tried the step below. please correct it as it is not working.
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#parent, :html => { multipart: true, class: "form-horizontal", role: "form"}) do |f| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :email, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.email_field :email, class: "form-control", placeholder: "Enter email", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password, class: "form-control", placeholder: "Enter password", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password_confirmation, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password_confirmation, class: "form-control", placeholder: "Re-enter password", required: true %>
</div>
</div>
<%= f.hidden_field :admin, :value => true %>
<div class="form-group">
<div class="col-sm-10">
<%= f.submit 'Sign up', class: 'btn btn-primary btn-lg' %>
</div>
</div>
<% end %>
</div>
</div>
Parent controller
def addusers
#parent=Parent.new
end
Updated parent controller
def new
#parent = Parent.new
#parent.secondaryparents.build
add_breadcrumb "Home", :root_path
add_breadcrumb "Sign up"
end
def addusers
#parent=Parent.new
end
def create_users
#parent=Parent.new(parent_params)
#parent.admin = true
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please ask user to confirm email address to continue"
redirect_to main_admin_path
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to main_admin_path
end
end
def create
#parent = Parent.new(parent_params)
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please confirm your email address to continue"
redirect_to root_path(#parent)
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to signup_path
end
end
Routes
resources :parents do
resources :children do
resources :fundings
end
end
end
get 'signup', to:'parents#new'
get 'login', to: 'sessions#new'
get 'usersignup', to:'parents#addusers'
post 'usersignup', to:'parents#create_users'
resources :parents, except: [:new] do
member do
get :confirm_email
end
end
Remove hidden line from html page, no need it f.hidden_field :admin, :value => true
Form_for
form_for(#parent, url: usersignup_path,
:html => { multipart: true, class: "form-horizontal", role: "form"}) do |f|
Add to routes:
post 'usersignup', to:'parents#create_users'
Controller:
def create_users
#parent = Parent.new(parent_params)
#parent.admin = true
if #parent.save
#do yr logic here
else
redirect_back(fallback_location: "/", flash: { danger: "smth went wrong.." })
end
end
def parent_params
params.require(:parent).permit(:email, :password, :password_confirmation)
end

Rails join collection not recognizing parameters

I'm trying to create a record in a join table named Interventions. Basically in my application a user can do many interventions on an incident, and an incident can have interventions by many users. I pass the needed strong parameters, but the application gives the following errors when I try to save: "Incident must exist" and "User must exist". I spent hours on this, and can't figure out what is the problem. Can you please help me? I post the relevant code here:
user.rb (model)
has_many :interventions
has_many :incidents, through: :interventions
incident.rb (model)
has_many :interventions
has_many :users, through: :interventions
intervention.rb (model)
belongs_to :incident_priority
belongs_to :intervention_status
interventions_controller.rb
def new
#incident = Incident.find(params[:incident])
#user = User.find(current_user.id)
#intervention = Intervention.new(:user_id => #user, :incident_id => #incident)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
end
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
respond_to do |format|
if #intervention.save
format.html { redirect_to new_intervention_path(#incident), notice: 'Intervention was successfully created.' }
format.json { render :show, status: :created, location: #intervention }
else
format.html { render :new, incident: :incident_id }
format.json { render json: #intervention.errors, status: :unprocessable_entity }
end
end
end
< .... >
def intervention_params
params.require(:intervention).permit(:user_id, :incident_id, :incident_priority_id, :begin_date, :end_date, :description,
:intervention_status_id, :forwarded_to)
end
In my view (interventions_form.html.erb):
<%= form_for(#intervention) do |f| %>
<% if #intervention.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#intervention.errors.count, "error") %> prohibited this intervention from being saved:</h2>
<ul>
<% #intervention.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group form-inline">
<%= hidden_field_tag :user_id, #user.id %>
<%= hidden_field_tag :incident_id, #incident.id %>
<strong>Interveniente:</strong>
<%= #user.first_name %> <%= #user.last_name %>
</div>
<div class="form-group form-inline">
<%= f.label 'Prioridade' %>
<%= f.collection_select :incident_priority_id, IncidentPriority.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data início intervenção' %>
<%= f.datetime_select :begin_date %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data fim intervenção' %>
<%= f.datetime_select :end_date, :include_blank => true %>
</div>
<div class="form-group form-inline">
<%= f.label 'Observações' %>
<%= f.text_area :description %>
</div>
<div class="form-group form-inline">
<%= f.label 'Estado' %>
<%= f.collection_select :intervention_status_id, InterventionStatus.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Encaminhado para:' %>
<%= f.text_area :forwarded_to %>
</div>
<div class="actions" align="right">
<%= link_to 'Voltar', incidents_path(:mirth => #mirth, :project => #project), class: "btn btn-info" %>
<%= f.submit "Gravar", class: "btn btn-info" %>
</div>
I run debug and the values in the hidden_field_tags are correctly filled. Also in the controller the #user and #incident are correctly populated, but #intervention has nil in the foreign keys :user_id and :incident_id.
Thanks in advance!
You need to associate the user and the incident with the intervention.
in your model...
class Intervention
belongs_to :user
belongs_to :incident
in your create method...
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#intervention.incident = #incident
#intervention.user = #user
...
You need to change this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
# ...
end
For this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
intervention_params.merge(user_id: #user.id, incident_id: #incident.id)
# ...
end
And your model:
class Intervention
belongs_to :user
belongs_to :incident

Authenticate with bcrypt for change password

Well, I got a problem to authenticate the user at the moment of changing his/her password, I get the mail and password and run the self.authenticate, but it keep returning me nil
I use the same format as when I log in. Here's the code
user_controller.rb
def change_pw
#user = User.authenticate(current_user.email, params[:password])
logger.info current_user.email
if #user.nil?
logger.info params[:password]
flash[:notice] = "incorrect password"
redirect_to :back
else
if #user.valid?
#user.password = #user.new_password unless #user.new_password.nil? || #user.new_password.empty?
#user.save
flash[:notice] = "Los cambios se han realizado exitosamente."
redirect_to #user
end
end
end
user.rb
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
return user
else
return nil
end
end
form
<%= form_for(#user, :url => "/change_password") do |f| %>
<%= hidden_field(:user, :email, :value => #user.email) %>
<div class="form-group">
<div class="form-group col-md-4"><%= f.label :password %></div>
<div class="form-group col-md-8"><%= f.password_field(:password, :class => "form-control") %></div>
</div>
<div class="form-group col-md-4"><%= f.label :new_password %></div>
<div class="form-group col-md-8"><%= f.password_field(:new_password, :class => "form-control") %></div>
<div class="form-group">
<div class="form-group col-md-4"><%= f.label :new_password_confirmation %></div>
<div class="form-group col-md-8"><%= f.password_field(:new_password_confirmation, :class => "form-control") %></div>
</div>
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Change Password</button>
</div>
<% end %>
I'm just trying to figure it out why it keeps returning me nil and how I can success on change password.
I finally found the reason of all my problems
def change_pw
#user = User.authenticate(current_user.email, params[:user][:password])
if #user.nil?
flash[:notice] = "Contraseña incorrecta"
redirect_to :back
else
if #user.valid?
#user.password = params[:user][:new_password] unless params[:user][:new_password].nil? || params[:user][:new_password].empty?
#user.save
redirect_to #user
end
end
end
There's the way to solve it, i had to specified the params directly and that's all

Resources