rails 3 flash message not displayed on mobile - ruby-on-rails-3

My app enables images uploading.
The user , if successful , receives a success message:
the controller:
def create
#rating = Rating.new(params[:rating])
respond_to do |format|
if #rating.save
format.html { redirect_to #rating, :notice => 'Got It!',
:flash => {:notice_small => 'Your photo has been uploaded. good luck with its coolness rating!'} }
format.json { render :json => #rating, :status => :created, :location => #rating }
else
format.html { render :action => "new" }
format.json { render :json => #rating.errors, :status => :unprocessable_entity }
end
end
end
the view:
<br>
<br>
<div style="height: 100px;" class="visible-tablet visible-phone"></div>
<p id="notice" class="big_notice"><%= notice %></p>
<% if defined? flash[:notice_small] %>
<p id="small_notice" class="small_notice"><%= flash[:notice_small] %></p>
<% end %>
which works fine on desktop. but not on mobile :-(
the pictures are uploaded but i just don't get the confirmation message
Edit:
I viewed the source on mobile and displays the html like so
<p id="notice" class="big_notice"></p>
<p id="small_notice" class="small_notice"></p>
meaning that the flash[:notice_small] is defined(notice the if defined? flash[:notice_small] condition) but it's just empty

Related

Rails update in different controller

Hello im doing simple update..
logged_customer_controller.rb
class LoggedCustomerController < ApplicationController
before_filter :authorize
helper_method :current_customer
layout "frontend"
def current_customer
#current_customer ||= Customer.find(session[:customer_id]) if session[:customer_id]
end
def authorize
if session[:auth] != true
redirect_to login_path, :notice => "Not logged."
end
end
def show
end
def edit
end
def update
respond_to do |format|
if current_customer.update_attributes(params[:current_customer])
format.html { redirect_to view_path, notice: 'Customer was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: current_customer.errors, status: :unprocessable_entity }
end
end
end
end
routes.rb
match "view" => "logged_customer#show", :via => :get
match "edit" => "logged_customer#edit", :via => :get
match "edit" => "logged_customer#edit", :via => :put
edit.html.erb
<%= form_for current_customer, :url => url_for(:controller => 'logged_customer', :action => 'edit'), :html => { :class => 'form-horizontal' } do |f| %>
<% if current_customer.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(current_customer.errors.count, "error") %>.
</div>
<ul>
<% current_customer.errors.full_messages.each do |msg| %>
<li> <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
...
I can display localhost:3000/view where is edit button. At localhost:3000/edit the form is displayed with autofilled informations, everything looks good. When i click on submit button im redirected to same edit autofilled form but WITHOUT any error ? So i guess there is some mistake because updating failed and another mistake that it dont render errors. What im doing wrong ?
I have logged_customer_controller.rb because customer_controller.rb is for administration purposes and is under authorization.
at Development.log i have only (looks good)
Started PUT "/edit" for 127.0.0.1 at 2013-08-19 14:54:30 +0200
Processing by LoggedCustomerController#edit as HTML
Parameters: {...}
<Executing SQL ...>
Rendered logged_customer/edit.html.erb within layouts/frontend (67.0ms)
Completed 200 OK in 89ms (Views: 33.0ms | ActiveRecord: 56.0ms)
Well, on your form_for you say that the action is the edit one, when it should be update.
<%= form_for current_customer,
:url => url_for(:controller => 'logged_customer', :action => 'edit'),
:html => { :class => 'form-horizontal' } do |f| %>
This way, when you submit it would hit the edit action. Change this and you are good to go.
Also, change you route as #Mattherick said:
match "update" => "logged_customer#update", :via => :put
Change your routes (rails 3):
match "view" => "logged_customer#show", :via => :get
match "edit" => "logged_customer#edit", :via => :get
match "update" => "logged_customer#update", :via => :put
Change your routes (rails 4):
get "view" => "logged_customer#show"
get "edit" => "logged_customer#edit"
patch "update" => "logged_customer#update"
Change your form:
<%= form_for current_customer, :url => url_for(:controller => 'logged_customer', :action => 'update'), :method => "patch", :html => { :class => 'form-horizontal' } do |f| %>
<%= # your form fields %>
<% end %>

Passing JQuery Datepicker Data to Rails Controller

I'm new to Rails and JQuery so I'll try to explain this as best I can. I'm trying to pass my JQuery datepicker values to my rails controller. The page has data on it that I want the user to be able to filter based on a date range. There are a number of different posts on this subject:
Passing the variables from from jquery to rails controller
How to pass variables from AJAX form into controller?
I have tried to follow the guidance of these posts, but I'm still having trouble.
Here is my partial _dateFilter.html.erb =>
<%= form_tag({:controller => 'events', :action => 'dateFilter', :class => 'date_form'}, :remote => true) do %>
<%= datepicker_input "event", :start_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= datepicker_input "event", :end_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= submit_tag "Submit" %>
<% end %>
Here is the generated HTML =>
<form accept-charset="UTF-8" action="/events/dateFilter?class=date_form" data-remote="true" method="post">
<input class="dateFilter" id="event_start_date" name="event[start_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_start_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input class="dateFilter" id="event_end_date" name="event[end_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_end_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input name="commit" type="submit" value="Submit" />
</form>
Here is the dateFilter.js.erb =>
$('.dateFilter').append('<%= escape_javascript(render(#events)) %>');
Here is the events_controller =>
def dateFilter
#events = Event.find(:all, :conditions => ["EVENT_DATE_TIME_LOCAL BETWEEN ? AND ?", params[:start_date], params[:end_date]])
respond_to do |format|
format.html
format.json { render json: #events }
format.js
end
end
Finally here is the application.js =>
$(document).ready(function() {
$('#date_form').submit(function (){
$.ajax({
type: 'POST',
url: "/events/dateFilter",
beforeSend: function (xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
data: { 'start_date' : $("input[name='event[start_date]']").datepicker(), 'end_date' : $("input[name='event[end_date]']").datepicker()}
success: function(data) { <%= render "events/dateFilter" %>}
});
});
This is log data from the server =>
Started POST "/events/dateFilter?class=date_form" for 127.0.0.1 at 2012-12-12 15:09:39 -0500
Processing by EventsController#dateFilter as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"J/HU+DxNmIwEhu3keN071k6MGCCD/n/1UhXUD0MkH1Q=", "event"=>{"start_date"=>"12/06/12", "end_date"=>"12/13/12"}, "commit"=>"Submit", "class"=>"date_form"}
Event Load (1.7ms) SELECT "TBLEVENT".* FROM "TBLEVENT" WHERE (EVENT_DATE_TIME_LOCAL BETWEEN NULL AND NULL)
Rendered collection (0.0ms)
Rendered events/dateFilter.js.erb (0.3ms)
Completed 200 OK in 8ms (Views: 3.4ms | ActiveRecord: 1.7ms)
One of the problems is that I keep getting "NULL" for the values of data I am trying to pass. I'm not even sure that I am going about this correctly, any help/feedback on this would be greatly appreciated. Thanks.
From your log data, this is in the Parameters:
"event"=>{"start_date"=>"12/06/12", "end_date"=>"12/13/12"}
which means start_date and end_date are in a Hash called event, so your controller should look like this:
def dateFilter
eventIn = params[:event]
#events = Event.find(:all, :conditions => ["EVENT_DATE_TIME_LOCAL BETWEEN ? AND ?", eventIn[:start_date], eventIn[:end_date]])
respond_to do |format|
format.html
format.json { render json: #events }
format.js
end
end
One other small thing - the form_tag class should be set like so:
<%= form_tag({:controller => 'events', :action => 'dateFilter'}, :class => 'date_form', :remote => true) do %>

Validation in twitter/bootstrap modal rails 3.2

I am trying to get validation to return in my modal using rails 3.2,twitter/bootstrap and formtastic, but I am at a loss as to how to do this.
Below is a quick sample of what my modal and form look like. In the model I require firstname and lastname. If the user hits 'submit' without putting in a firstname or lastname, it immediately takes the user to my actual registration page and notifies them of what is missing.
But I would like it to return to this modal and let the user know what is missing. How do I accomplish this?
:In my header, this is how I bring up the modal:
=link_to 'Register', "#new_registration_modal", :data => { :toggle => "modal",:backdrop => "static" }
#app/views/subscribers/registration/_new_modal.html.haml
#new_registration_modal.modal.hide.fade
.modal-header
Some Text
.modal-body
Some Text
=semantic_form_for(:subscriber, :as => resource_name, :url => registration_path(resource_name),:html => { :class => "form-inline" } ) do |f|
=f.input :email
=f.input :firstname
=f.input :lastname
=f.input :password
=f.input :password_confirmation
=f.submit
.modal-footer
Some Text
I have found a solution working for my side (using simple_form), maybe can help you:
I want to add a new client inside a modal from another controller.
The view of the modal controller:
<div id="client_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="client_modal_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="client_modal_label">Create new client</h3>
</div>
<div class="modal-body">
<%= simple_form_for Client.new, html: {"data-type" => :json}, remote: true do |f| %>
<div id="error_explanation" style="display:none;"></div>
<div class="form-inputs">
# the inputs
# ... and "closing" the modal
The client_controller.create:
def create
# save the data
if #client.save
respond_to do |format|
format.html { redirect_to anagrafe_index_path, :notice => "Client create!"}
format.json { render json: #client, status: :created, location: #client }
end
else
respond_to do |format|
format.html { render :action => 'new'}
format.json { render json: #client.errors.full_messages, status: :unprocessable_entity }
end
end
end
The js.coffee where the modal is raised:
$ ()->
$("form.new_client").on "ajax:success", (event, data, status, xhr) ->
$("form.new_client")[0].reset()
$('#client_modal').modal('hide')
$('#error_explanation').hide()
$("form.new_client").on "ajax:error", (event, xhr, status, error) ->
errors = jQuery.parseJSON(xhr.responseText)
errorcount = errors.length
$('#error_explanation').empty()
if errorcount > 1
$('#error_explanation').append('<div class="alert alert-error">The form has ' + errorcount + ' errors.</div>')
else
$('#error_explanation').append('<div class="alert alert-error">The form has 1 error.</div>')
$('#error_explanation').append('<ul>')
for e in errors
$('#error_explanation').append('<li>' + e + '</li>')
$('#error_explanation').append('</ul>')
$('#error_explanation').show()

Problem with nested form sign-up process

After researching on SO, I found that I desire a sign-up process that goes:
User fills out form
User clicks 'Join'
User is created/logged in and redirected to fill out profile
Button clicked
User directed to profile
If I were to create a User and User's Profile in rails console it would look like this:
user = User.new
user.email = ""
user.password = ""
user.profile = Profile.new
user.profile.info = ""
user.profile.save
user.save
THE PROBLEM: I'm using a nested model form on the homepage to create the user and add that user's profile first/last name. What happens now is: The user clicks 'Join', they are redirected to /users, then redirected to /signup. That's where I'm stuck. It gives me the following error:
Action Controller: Exception caught
NoMethodError in ProfilesController#new
undefined method `profile=' for nil:NilClass
app/controllers/profiles_controller.rb:5:in `new'
I want /signup to be a form to fill in the profile but it's not working.
My code below...
Users#new.html.erb (homepage form):
<%= form_for(#user, :html => {:multipart => true, :id => 'homesign'}) do |f| %>
<%= f.hidden_field :id %>
<% if #user.errors.any? %>
<% end %>
<div>
<%= f.label :email %>
<%= f.text_field :email, :size => 38 %>
</div>
...
<%= f.fields_for :profile do |profile| %>
<%= profile.label :first_name %>
<%= profile.text_field :first_name, :size => 18 %>
...
<% end %>
<% end %>
Profiles#new.html.erb (signup form):
<%= form_for #profile, :html => { :multipart => true } do |f| %>
<table id="signupTable">
<tbody>
<tr>
<td class="label"><%= f.label :gender, "Gender:" %></td>
<td>
<fieldset>
<%= select(:gender, :gender_type, [['Female', 1], ['Male', 2], ['Rather not say', 3]], :class => 'optionText') %>
</fieldset>
</td>
</tr>
<tr>
<td class="label"><%= f.label :birthday, "Birthday:" %></td>
<td>
<fieldset>
<%= select_month(14, :prompt => 'Month', :field_name => 'Month', :id => 'Date.mon') %>
<%= select_day(32, :prompt => 'Day') %>
<%= select_year(0, {:prompt => "Year", :start_year => DateTime.now.year, :end_year => DateTime.now.year - 115}, {:field_name => 'Year', :id => 'Date.year'}) %>
</fieldset>
<% end %>
User.rb:
class User < ActiveRecord::Base
attr_accessor :password
has_one :profile, :dependent => :destroy
accepts_nested_attributes_for :profile
validates :email, :uniqueness => true,
:length => { :within => 5..50 },
:format => { :with => /^[^#][\w.-]+#[\w.-]+[.][a-z]{2,4}$/i }
validates :password, :confirmation => true,
:length => { :within => 4..20 },
:presence => true,
:if => :password_required?
end
Profile.rb:
class Profile < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
UsersController:
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
def new
#user = User.new
#user.profile = Profile.new
if logged_in?
redirect_to current_user.profile
end
end
def index
#user = User.all
end
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = user.id
redirect_to new_user_profile_path(:user_id => #user), :notice => 'User successfully added.'
else
render :action => 'new'
end
end
end
ProfilesController:
class ProfilesController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
def new
#user.profile = Profile.new
end
def create
#profile = Profile.new(params[:profile])
if #profile.save
redirect_to profile_path(#profile), :notice => 'User successfully added.'
else
render :action => 'new'
end
end
def index
#profile = current_user.profile
end
end
SessionsController (create only):
class SessionsController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to user.profile, :notice => "Logged in successfully"
else
flash.now[:alert] = "Invalid login/password. Try again!"
render :action => 'new'
end
end
end
Routes.rb:
match "/signup" => "profiles#new", :as => "signup"
post "/profiles/new" => "profiles#create"
match "skip/signup", :to => "info#signupskip"
match "skip/profiles/new", :to => "profiles#newskip"
get "/profiles/:id" => "profiles#show", :as => "profile"
get "profiles/new"
root :to => "users#new"

How to retrieve data via ajax request and display the result into the next tag?

I using jQuery and have the following code, it's a partial and I want to know how could I retrieve a specific data on the onchange method and display the result into the next tag. (inside the span tag)
NOTE: this select field are generated on-the-fly, so, I can have N id's.
<p class="fields">
<%= f.collection_select(:part_id, #parts, :id, :title, { :prompt => true } , { :onchange => "?" } ) %>
<span class='part_price'> _ _ _ _ </span>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
Also I've created the method for this action (I don't know if this is right):
def retrieve_part_price
#price = Part.find(params[:id])
respond_to do |format|
format.html { redirect_to(items_path)}
format.json { render #price }
end
end
And put that on the routes.rb:
resources :items do
member do
get :update_part_price
end
end
Solved.
my partial:
<p class="fields">
<%= f.collection_select(:part_id, #parts, :id, :title, { :prompt => true } , { :onchange => "load_part_price_select(this.id, this.options[this.selectedIndex].value);" } ) %>
<%= f.label(:part_id, "Price: ") %>
<span class="price"></span>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
application.js
function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
$.ajax({
url: '/parts/' + value + '/price',
type: 'get',
context: this,
dataType: 'script',
success: function(responseData) {
$(this).nextAll("span.price:first").html(responseData);
}
});
});
};
controller:
def price
#price = Part.find(params[:id])
respond_to do |format|
format.js { render :text => #price.price }
end
end