Rails 3.2
In lib/model_extension.rb, I have:
module ModelExtension
def generate_model_id
self.id = "#{Time.now.to_f.to_s.gsub /\./, '_'}_#{self.class.name.underscore}" if id.blank?
end
def add_ticket_id_to_model(ticket_id)
self.ticket_id = ticket_id
end
end
In controllers/admin/lead_billings_controller.rb, I have:
def create
#lead_billing = LeadBilling.new(params[:lead_billing])
#lead_billing.generate_model_id
#lead_billing.add_ticket_id_to_model(ticket_id)
#ticket = Ticket.find(params[:ticket_id])
respond_to do |format|
if #lead_billing.save
format.html { redirect_to #ticket, notice: 'Lead billing was successfully created.' }
format.json { render json: #lead_billing, status: :created, location: #lead_billing }
else
format.html { render action: "new" }
format.json { render json: #lead_billing.errors, status: :unprocessable_entity }
end
end
end
In models/lead_billing.rb, here's what I have:
class LeadBilling < ActiveRecord::Base
include ModelExtension
attr_accessible :ticket_id, :pre_tax_total, :post_tax_total
belongs_to :ticket
end
In views/lead_billings/leadbillings.html.slim, I have:
- pre_tax_total = #ticket.lead_billing.pre_tax_total.to_f
- post_tax_total = #ticket.lead_billing.post_tax_total.to_f
table.table.ajax-table.show-mode
tr.head-row
th Pre-Tax Total
th Post-Tax Total
tr
td = number_to_currency(pre_tax_total, :unit => "$")
td = number_to_currency(post_tax_total, :unit => "$")
- if lead_billing.status == 'entered'
= form_for(LeadBilling.new, url: lead_billing_path) do |f|
= hidden_field_tag :ticket_update_type, "complete_and_generate_lead_invoices"
= hidden_field_tag :ticket_id, #ticket.id
.form-horizontal-column.customer-info
.form-group
.form-horizontal-column.customer-info
.actions = f.submit 'Complete And Generate Invoices'
.clear
When I fill and submit the form, I get an error message, and this is what I have in the log file:
Started POST "/admin/lead_billings" for 162.17.182.1 at 2016-12-01 18:36:01 +0000
Processing by Admin::LeadBillingsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "ticket_update_type"=>"save_lead_billing", "ticket_id"=>"1473264666_2463856_ticket", "lead_billing"=>{"pre_tax_total"=>"100", "post_tax_total"=>"120"}, "commit"=>"Save Lead Billing Details"}
.......................
NameError (undefined local variable or method `ticket_id' for #<Admin::LeadBillingsController:0x0000000919e368>):
app/controllers/admin/lead_billings_controller.rb:44:in `create'
app/middleware/catch_json_parse_errors.rb:8:in `call'
I double checked the lead_billings table and it has the ticket_id column.
Any ideas?
in your controller #lead_billing.add_ticket_id_to_model(ticket_id) you missed to either set ticket_id or just say params[:ticket_id] on that line
Related
I have a ruby on rails app. I added date_field to the view for add/Edit dates. the problem is that I have problem for saving and updating new dates but it brings the date from variable to the form(Edit) and after editting a date and creatine a new date. it doesn't come back to the home page or have problem with saving. as I saw in the console params, my date variable(start) changed when the user select new date but it does not load the first page afterward and I got this error:
F, [2018-02-01T16:03:44.784113 #723] FATAL -- :
NoMethodError (undefined method `year' for nil:NilClass):
app/controllers/weeks_controller.rb:27:in `create'
here is my form page where it shows date to edit:
.form-group
= f.label :course
= #course.name
.form-group.form-inline
= f.label :start
= f.date_field :start, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control'
//= f.date_select :start, {}, { :class => "form-control" }
.actions
= f.submit 'Save', :class => "btn btn-primary"
an the error says about controller. but I do not have any 'year' method in controller:
def create
#week = Week.new(week_params.merge(course_id: #course.id))
respond_to do |format|
if #week.save
format.html { redirect_to '/weeks', notice: 'was successfully created.' }
format.json { render action: 'show', status: :created, location: #week }
else
format.html { render action: 'new' }
format.json { render json: #week.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #week.update(week_params)
format.html { redirect_to '/weeks', notice: 'starting week was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #week.errors, status: :unprocessable_entity }
end
end
end
weeks_params defined as follows:
def week_params
params.require(:week).permit(:start, :course_id)
end
I have at first problem of showing date with date_select but now with date_field it shows that but I do not know where this error refers to. I would be thankful if any one would help me.
The model is:
class Week < ActiveRecord::Base
belongs_to :course
has_many :assessments
def select_name
start.strftime("Week of %b %d")
end
end
I am creating an ruby on rails 5 application. It is a todolist kind of application and using simple_form, haml-rails and cocoon gem. This is a application with nested form.
Generated a scaffold for goal and created model for action
Goal.rb and Action.rb
class Goal < ApplicationRecord
has_many :actions
accepts_nested_attributes_for :actions, reject_if: :all_blank
end
class Action < ApplicationRecord
belongs_to :goal
end
Then added the actions_attribute to permit in the params
class GoalsController < ApplicationController before_action :set_goal, only: [:show, :edit, :update, :destroy] def index
#goals = Goal.all end def show end def new
#goal = Goal.new end def edit end def create
#goal = Goal.new(goal_params)
respond_to do |format|
if #goal.save
format.html { redirect_to #goal, notice: 'Goal was successfully created.' }
format.json { render :show, status: :created, location: #goal }
else
format.html { render :new }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end end def update
respond_to do |format|
if #goal.update(goal_params)
format.html { redirect_to #goal, notice: 'Goal was successfully updated.' }
format.json { render :show, status: :ok, location: #goal }
else
format.html { render :edit }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end end def destroy
#goal.destroy
respond_to do |format|
format.html { redirect_to goals_url, notice: 'Goal was successfully destroyed.' }
format.json { head :no_content }
end end private
def set_goal
#goal = Goal.find(params[:id])
end
def goal_params
params.require(:goal).permit(:name, :purpose, :deadline, actions_attributes: [:step])
end
end
Forms for both form.html and action.html
_form.html.haml
= simple_form_for(#goal) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :purpose
= f.input :deadline
%h3 Actions
#tasks
= f.simple_fields_for :actions do |action|
= render 'action_fields', f: action
.links
= link_to_add_association 'Add', f, :actions
.form-actions
= f.button :submit
// action.html.haml
.nested-fields
= f.input :step
= f.input :done, as: :boolean
= link_to_remove_association "remove task", f
log in the console when i submit form
Processing by GoalsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jel0g+oCkNaspe7T9dz7suDczIOdoKJqPqPDK9ta0WLPbwaSPBwshrDD2BrNAFeLoDx+0/soe11MWaZaH8cQoA==", "goal"=>{"name"=>"ja", "purpose"=>"asdfd", "deadline"=>"asdfasd", "actions_attributes"=>{"0"=>{"step"=>"ARasd", "done"=>"1", "_destroy"=>"false"}, "1475080334356"=>{"step"=>"", "done"=>"0", "_destroy"=>"false"}}}, "commit"=>"Create Goal"}
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
(0.5ms) BEGIN
(0.5ms) ROLLBACK
Rendering goals/new.html.haml within layouts/application
Rendered goals/_action_fields.html.haml (18.5ms)
Rendered goals/_action_fields.html.haml (26.5ms)
Rendered goals/_action_fields.html.haml (19.0ms)
Rendered goals/_form.html.haml (252.5ms)
Rendered goals/new.html.haml within layouts/application (309.0ms)
Completed 200 OK in 932ms (Views: 898.5ms | ActiveRecord: 1.0ms)
The console log shows: Unpermitted parameter: done
This is because in your controller, only these parameters are permitted:
params.require(:goal).permit(:name, :purpose, :deadline, actions_attributes: [:step])
Error: Unpermitted parameter: properties
I'm whitelisting the properties{} in the request_controller.rb
This usually works but not this time.
I'm not been able to save some of the data entered in a form. The 3 fields that are not saving are coming from a dynamic form "request_type". I followed Rails Cast episode 403 for this solution, which I have working well in another project but not in this one.
Source: http://railscasts.com/episodes/403-dynamic-forms
Sorry if this is a duplicate question, but I've looked at several other questions and I can't pin-point what I'm doing wrong here
I've researched several questions here, but I'm still not able to get it to work:
Rails 4 Nested Attributes Unpermitted Parameters
Nested attributes - Unpermitted parameters Rails 4
I'm omitting some stuff to make it easier to read the code. Please ask me if you need to see more.
Here's the log:
Processing by RequestsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8EASewOIxY58b+SU+dxd2YAfpjt38IdwNSju69RPwl/OKfx3AfmvLav79igj8CqPbDwi0eJAwojRbtm+C9F6wg==", "request"=>{"name"=>"asdasddaa", "due_date(1i)"=>"2016", "due_date(2i)"=>"9", "due_date(3i)"=>"15", "user_id"=>"1", "project_id"=>"1", "request_type_id"=>"2", "properties"=>{"Name and last name"=>"asdasd", "Mobile"=>"asdada", "Office tel."=>"asdadas"}}, "commit"=>"Create Request"}
Unpermitted parameter: properties
Update
If I change the request_params to this:
def request_params
params.require(:request).permit(:name, :due_date, :group_id, :user_id, :project_id, :request_type_id, properties:{} ).tap do |whitelisted|
whitelisted[:properties] = params[:request][:properties]
end
end
See:
properties:{}
I get this Error:
Unpermitted parameters: Name and last name, Mobile, Office tel.
request_controller.rb
def new
#request = Request.new
#request_type = RequestType.find(params[:request_type_id])
#project = #request_type.project.id
end
def create
#request = Request.new(request_params)
respond_to do |format|
if #request.save
format.html { redirect_to #request, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: #request }
else
format.html { render :new }
format.json { render json: #request.errors, status: :unprocessable_entity }
end
end
end
def request_params
params.require(:request).permit(:name, :due_date, :group_id, :user_id, :project_id, :request_type_id, :properties).tap do |whitelisted|
whitelisted[:properties] = params[:request][:properties]
end
end
request_types_controller.rb
def new
#request_type = RequestType.new
#project = Project.find(params[:project])
end
def create
#request_type = RequestType.new(request_type_params)
respond_to do |format|
if #request_type.save
format.html { redirect_to #request_type, notice: 'Request type was successfully created.' }
format.json { render :show, status: :created, location: #request_type }
else
format.html { render :new }
format.json { render json: #request_type.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #request_type.update(request_type_params)
format.html { redirect_to #request_type, notice: 'Request type was successfully updated.' }
format.json { render :show, status: :ok, location: #request_type }
else
format.html { render :edit }
format.json { render json: #request_type.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_request_type
#request_type = RequestType.find(params[:id])
end
def request_type_params
params.require(:request_type).permit(:name, :project_id, properties:{}, fields_attributes: [:name, :field_type, :required, :id, :_destroy])
# params.require(:product_type).permit(:name, :product_type_id)
end
models/request.rb
class Request < ApplicationRecord
belongs_to :group
belongs_to :user
belongs_to :project
belongs_to :request_type
serialize :properties, Hash
end
models/request_type.rb
class RequestType < ApplicationRecord
belongs_to :project
has_many :fields, class_name: "RequestField"
accepts_nested_attributes_for :fields, allow_destroy: true
has_many :requests
end
models/request_field.rb
class RequestField < ApplicationRecord
belongs_to :request_type
end
views/requests/new.html.erb
<%= form_for #request do |f| %>
<%= f.fields_for :properties, OpenStruct.new(#request.properties) do |builder| %>
<% #request_type.fields.each do |field| %>
<%= render "requests/fields/#{field.field_type}", field: field, f: builder %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit class:"btn btn-primary" %>
</div>
<% end %>
Try removing :properties from your request_params in your request_controller like this:
def request_params
params.require(:request).permit(:name, :due_date, :group_id, :user_id, :project_id, :request_type_id).tap do |whitelisted|
whitelisted[:properties] = params[:request][:properties]
end
EDIT
def request_params
params.require(:request).permit(:id, :name, :due_date, :group_id, :user_id, :project_id, :request_type_id)
params.require(:properties).permit!
end!
I have this:
<%= f.association :gestor, selected: current_usuario.gestor_id, label_method: :descricao, value: current_usuario.gestor_id, disabled: true %>
My controller:
def create
#usuario = Usuario.new(usuario_params)
respond_to do |format|
if #usuario.save
format.html { redirect_to controle_usuarios_path, notice: 'Usuario was successfully updated.' }
format.json { render :index, status: :ok, location: #usuario }
else
format.html { render :new }
end
end
end
(...)
def usuario_params
params.require(:usuario).permit(:cpf, :usuario_pai, :gestor_id, :email, :password, :password_confirmation, :agente_id, :perfil_id)
end
And console:
Processing by ControleUsuariosController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xnMQOvRLO3cCrq/l5KSSG0qB3Pc8S4wtSgs4PTCTkaJ5kLLwMD73s/4TeBWYYbvmBKzvBca4T0eMT9F9UQo/Ew==", "usuario"=>{"usuario_pai"=>"admin#mail.com", "agente_id"=>"2", "cpf"=>"111.111.111-11", "email"=>"xxx#xxx.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "perfil_id"=>"2"}, "commit"=>"Criar Usuario"}
The params gestor_id don't come, why? The error is this:
Usuario(#70271925151780) expected, got String(#3432540)
Rails is looking for gester_id and you are passing in gester as the param so it is being removed. Try changing it in your view to gester_id or in your params filter to gester.
I'm a bit new in ruby/rails/POO and I'm a bit lost in a form that I'm realizing.
I'm using the gem formtastic and I'm doing it in haml.
I have this model
class Help < ActiveRecord::Base
attr_accessible :answer, :category, :question
validates :category, presence: true, uniqueness: true
validates :question, presence: true
validates :answer, presence: true
end
In my form, I want the possibility to create a new Question/Answer with its category.
The category should be selected in a selectbox but if the category I want is not listed yet, I want to have the ability to add it.
Here's the form
= semantic_form_for #help do |f|
= f.inputs do
= f.input :category, :as => :select, :collection => Help.category
= f.input :category
= f.input :question
= f.input :answer
= f.action :submit, :as => :button
EDIT :
class HelpsController < ApplicationController
# GET /helps
# GET /helps.json
def index
#helps = Help.all.sort_by {|f| f.category}
respond_to do |format|
format.html # index.html.erb
format.json { render json: #helps }
end
end
# GET /helps/1
# GET /helps/1.json
def show
#help = Help.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #help }
end
end
# GET /helps/new
# GET /helps/new.json
def new
#help = Help.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #help }
end
end
# GET /helps/1/edit
def edit
#help = Help.find(params[:id])
end
# POST /helps
# POST /helps.json
def create
#help = Help.new(params[:help])
respond_to do |format|
if #help.save
format.html { redirect_to #help, notice: 'Help was successfully created.' }
format.json { render json: #help, status: :created, location: #help }
else
format.html { render action: "new" }
format.json { render json: #help.errors, status: :unprocessable_entity }
end
end
end
# PUT /helps/1
# PUT /helps/1.json
def update
#help = Help.find(params[:id])
respond_to do |format|
if #help.update_attributes(params[:help])
format.html { redirect_to #help, notice: 'Help was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #help.errors, status: :unprocessable_entity }
end
end
end
# DELETE /helps/1
# DELETE /helps/1.json
def destroy
#help = Help.find(params[:id])
#help.destroy
respond_to do |format|
format.html { redirect_to helps_url }
format.json { head :no_content }
end
end
end
When I try to reach /help/new it actually says to me :
undefined method `model_name' for NilClass:Class
The aim is to have in the selectbox, categories already registered, and if the user is not founding the category he wants to use in the selectbox, he can create one by typing it in the input.
Any clues to help me doing this ?
Cordially ,
Rob
Try this:
= f.collection_select :category
I found a method that does half what i wanted.
It's the method pluck.
I defined a static method in my model :
def self.getcat
Help.pluck(:category)
end
Then in my form in simply call this method on my collection :
= f.input :category, :as => :select, :collection => Help.getcat