I am using ajax-rails to render my form and validations stopped working. When I click to submit empty for which should validate, validation does not take effect and backend log shows it posted empty form. If I don't use ajax it works fine. I don't know what I am missing.
model
class ClockEntry < ApplicationRecord
belongs_to :user
validates :purpose, presence: true # I validated the attribute
end
index.html.erb
<div class="container" id="new-clock-entry">
<%= link_to 'New Clock Entry', new_clock_entry_path, remote: true, class: 'btn btn-primary btn-sm' %>
</div>
_form.html.erb
<%= simple_form_for clock_entry, remote: true do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.input :purpose %>
</div>
<div class="form-actions">
<%= f.button :submit, class: 'btn btn-primary btn-block btn-lg' %>
</div>
<% end %>
new.html.erb
<h1>New Clock Entry</h1>
<%= render 'form', clock_entry: #clock_entry %>
<%= link_to 'Back', clock_entries_path %>
new.js.erb
$('#new-clock-entry a').hide().parent().append("<%= j render 'form', clock_entry: #clock_entry %>")
create.js.erb
$('#new-clock-entry form').remove();
$('#new-clock-entry a').show();
$('table#clock-entry tbody').append("<%= j render #clock_entry %>");
controller
def new
#clock_entry = ClockEntry.new
end
def create
#clock_entry = current_user.clock_entries.new(clock_entry_params)
#clock_entry.set_time_in
respond_to do |format|
if #clock_entry.save
format.js { redirect_to root_path, notice: 'Clock entry was successfully created.' }
format.html { redirect_to #clock_entry, notice: 'Clock entry was successfully created.' }
format.json { render :show, status: :created, location: #clock_entry }
else
format.html { render :new }
format.json { render json: #clock_entry.errors, status: :unprocessable_entity }
end
end
end
#arieljuod in the comments section was very instrumental to me solving this. As he mentioned firstly, I am not asking my format to respond to js under the else condition of the create method. So this is what I did:
controller create action
Add the line below to the else condition of the create action:
format.js { render :new }
So my controller action becomes:
def create
#clock_entry = current_user.clock_entries.new(clock_entry_params)
#clock_entry.set_time_in
respond_to do |format|
if #clock_entry.save
format.html { redirect_to #clock_entry, notice: 'Clock entry was successfully created.' }
format.js { redirect_to root_path, notice: 'Clock entry was successfully created.' }
format.json { render :show, status: :created, location: #clock_entry }
else
format.js { render :new } # Added this...
format.html { render :new }
format.json { render json: #clock_entry.errors, status: :unprocessable_entity }
end
end
end
new.js.erb file
Then in the new.js.erb file, upon rendering the :new form, you need to remove or hide what is already there and append a new form that has the error message. So I had to remove the whole form by supplying the form tag to be hidden in my new.js.erb. So I add this line below to my new.js.erb file:
$('#new-clock-entry form').hide().parent().append("<%= j render 'form', clock_entry: #clock_entry %>")
So new new.js.erb file now becomes:
$('#new-clock-entry a').hide().parent().append("<%= j render 'form', clock_entry: #clock_entry %>")
$('#new-clock-entry form').hide().parent().append("<%= j render 'form', clock_entry: #clock_entry %>")
I think this should be handy to anyone who runs into the same problem.
Related
I have a projects/show.html.erb page. A project has_many project_messages and from the projects/show.html.erb page, a user can create a new project_message successfully, however, when the new project_message is created through a _formpartial, the page refreshes.
I want to use :remote => true to add project_messages to the project without having to refresh the page.
Please see the code I used below. This does not work and the page still refreshes. I am new to rails so any help would be greatly appreciated.
Please see the code for each file below
In projects/show.html.erbto display the project_message and create a new project_message, I have the following code which is successful:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% #project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: #project_message } %>
</div>
</div>
In the project_messages_controller.rb file the create method is as follows, I have added format.js { }
def create
#project_message = ProjectMessage.new(project_message_params)
#project_message.user_id = current_user.id if current_user
#project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if #project_message.save
format.html { redirect_to #project_message.project }
format.json { render :show, status: :created, location: #project_message }
format.js { }
else
format.html { render :new }
format.json { render json: #project_message.errors, status: :unprocessable_entity }
end
end
end
The project_message _form partial then includes the :remote => true
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
I then created a new create.js.erb file in views/project_messages/create.js.erb and added the following code:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(#project_message) %>");
With the code above, the page still refreshes.
When I remove local: true from the project_message _form partial, it does not refresh and creates the model but the projects/show.html.erb view is not updated!
I used the following link here and also other posts on stackoverflow
respond_to do |format|
format.js { render 'project_messages/create.js'}
end
it seems you are using Rails 5
remove remote: true and local: true from your code
read about this in here
and make sure that you a html element with id = project_message
your code is $("#project_message").append("<%= j render(#project_message) %>");
so check your HTML code , is there any element with ID like that
you can use traditional form_for http://guides.rubyonrails.org/working_with_javascript_in_rails.html#remote-elements
update below code in your views
<%= form_for project_message, :remote => true do |form| %>
and make sure that you a html element with id like <div class="au-message-list" id="project_message">
I keep receving an error on my home page saying
'undefined method `company' for nil:NilClass'
for the first line of the following code displayed below. I am not really sure on how to fix this. I have two Controllers for both companies and customers because I am creating a two-sided marketplace.
When the user clicks the logo at the top instead of being redirected to the welcome page, the login page is being rendered since the home page is the root_path but I am using devise for before_action authenticate is being used.
<% if((current_user.company) || (current_user.customer)) %>
<%= render 'pages/welcome' %>
<% else %>
<% if current_user.is_company %>
<%= render 'companies/form', company: #company%>
<% else %>
Here is the home.html.erb file with the code which is the root_path
<% if((current_user.company) || (current_user.customer)) %>
<%= render 'pages/welcome' %>
<% else %>
<% if current_user.is_company %>
<%= render 'companies/form', company: #company%>
<% else %>
<%= render 'customers/form', customer: #customer%>
<% end %>
<% end %>
Here is my companiesController
class CompaniesController < ApplicationController
before_action :set_company, only: [:show, :edit, :update, :destroy]
def index
#companies = Company.all
end
# GET /companies/1
# GET /companies/1.json
def show
#company = Company.find(params[:company_id])
end
# GET /companies/new
def new
#company = Company.new
end
# GET /companies/1/edit
def edit
end
# POST /companies
# POST /companies.json
def create
#company = Company.new(company_params)
respond_to do |format|
if #company.save
format.html { redirect_to #company, notice: 'Company was successfully created.' }
format.json { render :show, status: :created, location: #company }
else
format.html { render :new }
format.json { render json: #company.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /companies/1
# PATCH/PUT /companies/1.json
def update
respond_to do |format|
if #company.update(company_params)
format.html { redirect_to #company, notice: 'Company was successfully updated.' }
format.json { render :show, status: :ok, location: #company }
else
format.html { render :edit }
format.json { render json: #company.errors, status: :unprocessable_entity }
end
end
end
# DELETE /companies/1
# DELETE /companies/1.json
def destroy
#company.destroy
respond_to do |format|
format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_company
#company = Company.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the
white list through.
def company_params
params.require(:company).permit(:username, :phone, :website, :street, :city, :state, :country, :user_id)
end
end
it just says that the current_user is nil, you need to make sure that the user is logged in to use current_user.company
The log is giving you details as to why the company is returning a nil. The company requires an object in it for the page to load properly. But that is not so because no user is logged in for the company to have an object to return.
<% if((current_user.company) || (current_user.customer)) %> <%=
render 'pages/welcome' %> <% else %>
<% if current_user.is_company %> <%= render 'companies/form',
company: #company%> <% else %>
is returning a nil because no user is logged in.
You can first check if there is a user logged in and then render
something before this to prevent the error page
<% if(current_user) <% if((current_user.company) ||
(current_user.customer)) %>
<%= render 'pages/welcome' %> <% else %>
<% if current_user.is_company %>
<%= render 'companies/form', company: #company%> <% end %> <% else %> render something here <% end %>
Or simply log in to make sure this does not return a nil. But the first fix is the most ideal.
I'm currently trying to use the nested form with cocoon, is awesome !! But I'm facing to an interrogation and I don't know which way I should take.
Relations :
Ranch have Cows
Ranch have Productions
Production have nested form Iproductions
What I'm trying to do now is implement my iteration |c| into each of my iproductions:cow_id elements
My code:
(My_form production)=
<%- #cows.each do |c| %>
<div class="row">
<div class="col-md-12">
<div id="Order">
<%= f.simple_fields_for :iproductions do |ip| %>
<%= render 'iproductions_fields', f: ip, cow: c %>
<%end%>
<div class="Order_links">
<%= link_to_add_association c.name, f, :iproductions, cow: c, class: "btn btn-default" %>
</div>
</div>
</div>
</div>
(My iproductions_fields)=
<div class="form-inline clearfix">
<div class="nested-fields">
<%= f.input :cow_id, :input_html => { :cow_id => :cow } %>
<%= f.input :quantity, input_html: {class: "form-input form-control"} %>
<%= link_to_remove_association "Supprimer", f, class: "form-button btn btn-default" %>
</div>
</div>
(My productions_controllers)=
class ProductionsController < ApplicationController
before_action :authenticate_user!
skip_before_action :configure_sign_up_params
before_action :set_ranch
before_action :set_production, except: [:create, :new, :show]
before_action :set_production2, only: [:show]
# GET /productions
# GET /productions.json
def index
#productions = Production.all
end
# GET /productions/1
# GET /productions/1.json
def show
#iproductions = Iproduction.where(id: params[:production_id])
end
# GET /productions/new
def new
#production = #ranch.productions.build
#cows = #ranch.cows
end
# GET /productions/1/edit
def edit
#cows = #ranch.cows
end
# POST /productions
# POST /productions.json
def create
#production = #ranch.productions.create(production_params)
#production.update(date: Date.today)
#cows = #ranch.cows
respond_to do |format|
if #production.save
format.html { redirect_to ranch_production_path(#production.ranch_id, #production), notice: 'Production was successfully created.' }
format.json { render :show, status: :created, location: #production }
else
format.html { render :new }
format.json { render json: #production.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /productions/1
# PATCH/PUT /productions/1.json
def update
respond_to do |format|
if #production.update(production_params)
format.html { redirect_to ranch_production_path(#production.ranch_id, #production), notice: 'Production was successfully updated.' }
format.json { render :show, status: :ok, location: #production }
else
format.html { render :edit }
format.json { render json: #production.errors, status: :unprocessable_entity }
end
end
end
# DELETE /productions/1
# DELETE /productions/1.json
def destroy
#production.destroy
respond_to do |format|
format.html { redirect_to ranch_productions_path(#production.ranch_id), notice: 'Production was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ranch
#ranch = Ranch.find(params[:ranch_id])
end
def set_production2
#production = Production.find_by(id: params[:id])
end
def set_production
#production = #ranch.productions.find_by(id: params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def production_params
params.require(:production).permit(:name, :ranch_id, :created_at, :date, iproductions_attributes: [:id, :date, :cow_id, :quantity, :_destroy])
end
end
My real view , so I would like to Assign each iproduction with the button which generate the iproductions_fields
So if you have any idea of which way I can try to achieve this goal, you're welcome,
Thanks in advance
I am trying to use cocoon gem to build nested forms.
I have models for Organisation, Package::Bip and Tenor.
The associations are:
Organisation
has_many :bips, as: :ipable, class_name: Package::Bip
accepts_nested_attributes_for :bips, reject_if: :all_blank, allow_destroy: true
Package::Bip (polymorphic)
belongs_to :ipable, :polymorphic => true, optional: true, inverse_of: :bip
has_one :tenor, as: :tenor
accepts_nested_attributes_for :tenor, reject_if: :all_blank, allow_destroy: true
Tenor (polymorphic)
belongs_to :tenorable, :polymorphic => true, optional: true
The forms have:
In my organisations/_form.html.erb, I have:
<%= f.simple_fields_for :bips do |f| %>
<%= f.error_notification %>
<%= render 'package/bips/bip_fields', f: f %>
<% end %>
<%= link_to_add_association 'Add another intellectual property resource', f, :bips, partial: 'package/bips/bip_fields' %>
In my bip_fields.html.erb nested form, I have:
<%# if #package_bips.tenor.blank? %>
<%= link_to_add_association 'Add timing', f, :tenor, partial: 'tenors/tenor_fields' %>
<%# end %>
<%= f.simple_fields_for :tenor do |tenor_form| %>
<%= f.error_notification %>
<%= render 'tenors/tenor_fields', f: tenor_form %>
<% end %>
Javascript
The cocoon docs suggest adding a js file to specify association-insertion-node as a function. In my tenor_subform.js I have:
$(document).ready(function() {
$(".add_tenor a").
data("association-insertion-method", 'append').
data("association-insertion-node", function(link){
return link.closest('.row').next('.row').find('.tenor_form')
});
});
Controllers
In my organisation controller, I have:
def new
#organisation = Organisation.new
#organisation.bips
end
Note: I'm not sure if I need to add another line to my new action to create the organisation.bip.tenor instance. I'm also unsure if im supposed to add has_one through association on the organisation.rb that references the tenor.
def organisation_params
params.fetch(:organisation, {}).permit(:title, :comment,
bips_attributes: [:id, :status, :_destroy,
tenor_attributes: [:id,:commencement, :expiry, :_destroy]
],
In my tenor controller, I have:
def tenor_params
params.require(:tenor).permit( :commencement, :expiry)
end
ERRORS
I am not sure if I need to add tenor actions to the organisation controller (the ultimate parent of bip which in turn is the parent of tenor).
When I save all of this and try it, I get an error that says:
unknown attribute 'tenor_id' for Tenor.
When I see other SO posts with this error, its often because the :id attribute hasn't been whitelisted in the parent class. I have done that.
Can anyone see what I've done wrong?
Tenor controller
class TenorsController < ApplicationController
before_action :set_tenor, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# after_action :verify_authorized
def index
#tenors = Tenor.all
# authorize #tenors
end
def show
end
def new
#tenor = Tenor.new
# authorize #tenor
end
def edit
end
def create
#tenor = Tenor.new(tenor_params)
# authorize #tenor
respond_to do |format|
if #tenor.save
format.html { redirect_to #tenor }
format.json { render :show, status: :created, location: #tenor }
else
format.html { render :new }
format.json { render json: #tenor.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #tenor.update(tenor_params)
format.html { redirect_to #tenor }
format.json { render :show, status: :ok, location: #tenor }
else
format.html { render :edit }
format.json { render json: #tenor.errors, status: :unprocessable_entity }
end
end
end
def destroy
#tenor.destroy
respond_to do |format|
format.html { redirect_to action: :index }
format.json { head :no_content }
end
end
private
def set_tenor
#tenor = Tenor.find(params[:id])
# authorize #tenor
end
def tenor_params
params.require(:tenor).permit(:express_interest, :commencement, :expiry, :enduring, :repeat, :frequency)
end
end
You has_one relation is wrongly declared. Because you say as: :tenor makes it look for a tenor_id.
You have to declare it as follows:
has_one :tenor, as: :tenorable
Your model does not see the id of nested_attr.Add :inverse_of => #{model}.
Example:
class Tenor < ActiveRecord::Base
has_many :traps, :inverse_of => :bips
end
For more information look this or this documentation.
I'm really new at working with AJAX. I'm trying to make a little status update type thing, similar to facebook or twitter. You post a status and it adds it to the list below you, and clears out the edit box.
The post is being added to the database just fine. The problem is the list of recent status messages is not being redrawn. I'm getting an error, ArgumentError (wrong number of arguments (2 for 1)).
I have tried to rewrite the js.erb several ways and it always has the error. Some assistance would be appreciated.
The Controller posts#create
def create
#post = Post.new(post_params)
#post.user_id = current_user.id
respond_to do |format|
if #post.save
#posts = Post.all
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.js render ##posts } # { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
The Partial _inline.html.erb /posts/inline
<div class="large-12 columns" id="inline_posts">
<% #posts.each do |post| %>
<div class="row">
<div class="large-10 columns left"><%= post.content %></div>
<div class="large-2 columns right"><%= link_to 'Remove', post, method: :delete, data: { confirm: 'Are you sure?' }, class: 'tiny button' %></div>
</div>
<% end %>
</div>
The Javascript create.js.erb
$("#inline_posts").html("<%= escape_javascript("render partial: 'posts/inline', posts: #posts ") %>")
Looks like if i change
format.js render
to
format.js
it works fine.
Sorry for the bother