mercredi 2 novembre 2016

How to create a windows service using Ruby?

One of my ruby developer created and hosted a web service, and he is starting the web service using the below command in the command prompt

>>cd c:\\web_service
>>mongrel_rails start -p 3002

he started ruby on rails server using the above command. The problem is if someone close the command prompt then the web service is getting stopped it leads to big issue.

My manager want to create a windows service to start the web service in background process.

I am new to this Ruby, Please help anyone help me about this ?

sum() or group() virtual attributes in ruby on rails

let's say I have a model like this:

class Surface < ActiveRecord::Base
  attr_accessible :width, :length

  def area
     self.width * self.length
  end
end

Where @surface.area returns the area of a surface. Now, lets say I have many surfaces called @surfaces and I want to sum all areas. How do I do this?

My favorite solution would look like this:

@surfaces.sum(:area)

But it does not work. So how can I call .sum() or .group() or any similar functions on a virtual attributes like this in rails? I would like to avoid .each do |surface| calls.

Thanks in advance.

Exclude Row from sorting - Datatables.net

I have a question about how to exclude a row(tr) from sorting. I want to make something like this http://ift.tt/2edPCQ9 but I don't want to set the data of the hidden row in jQuery. I suppose that you can do it adding a class to the element and after that manage to not sort this on initializing the datatable on jQuery. Actually I have the initialization like this:

$('.ordered_table').dataTable({
        "sPaginationType": "full_numbers",
        "dom": '<"toolbar">frtip',
        "pagingType": "numbers",
        "searching": false,
        "pageLength": 20,
        columnDefs: [{
          targets:  ['datatable-nosort'],
          orderable: false,  
          bsortable: false
        }],
        "aaSorting": []
 });

The class datatable-nosort is for not sorting on columns, this is not for rows.

Thanks to everyone!

Redirect routing wrong on :index action of controller

I am trying to apply a username validation on admin_projects_path by applying that application_controller filter into my controller which is extending the main class. When I redirect the page to root_path or any other routes things are going well. If I apply the filter only on :show action, that's going well as well. Why is the page rerouting me to the login again if I apply the filter on the :index action?

application_controller.rb

class ApplicationController < ActionController::Base

# Return the admin user
  def adminLogin
    email = params[:email]
    password = params[:password]
    if email == "username"
      redirect_to admin_projects_path
    else
      redirect_to admin_login_path unless request.fullpath == '/admin/login'
    end
  end
 end

projects_controller.rb

 class Admin::ProjectsController < ApplicationController
 before_filter :adminLogin

 # GET /admin/projects
 def index
   @projects = Project.all

   respond_to do |format|
     format.html # index.html.erb
   end
  end

 # GET /admin/projects/1
 # GET /admin/projects/1.json
 def show
   @project = Project.find(params[:id])

   respond_to do |format|
     format.html # show.html.erb
     format.json { render json: @project }
  end
 end

routes.rb

   match '/admin/login' => 'application#adminLogin'


   #Projects routes automatically generated - run 'rake routes' for more       
   info
   namespace :admin do
        resources :projects
   end

Saving sub object (via has_many) in create method rails

I've been trying to save sub-objects in a controller on my rails API.

My API is to create and organize congresses data.

One congres has one or many hotels, and hotels can have one or many hotel_various_infos.

The JSON I'm sending through POST /congresses is as following :

{
  "name": "Congress' name",
  "subtitle": "",
  "place": "cologne, germany",
  "date_from": "2016-10-22T00:00:00.000Z",
  "date_to": "2016-10-25T00:00:00.000Z",
  "host_company": "Hosting company",
  "host_logo_url": "http://ift.tt/2f0bUXn",
  "color" : "#121212",
  "template_id" : "1",
  "hotels": [
    {
      "name": "radisson blue Cologne",
      "address": "Messe Kreisel 3",
      "postal_code": "DE-50679",
      "city": "Cologne",
      "country": "Germany",
      "phone_nbr": "+49221277200",
      "check_in_time": "15:00",
      "check_out_time": "12:00",
      "hotel_various_infos": [
        {
            "title": "Welcome Desk",
            "content": "Should you require any assistance during your stay, a *** welcome desk will be open each day in the hotel lobby."
        }
      ]
    }
  ]
}

Here you can find my models :

congres.rb

class Congress < ApplicationRecord
  has_many :hotels, autosave: true
  has_many :agenda_events, autosave: true
end

hotel.rb

class Hotel < ApplicationRecord
  belongs_to :congress
  has_many :hotel_various_infos, autosave: true
end

hotel_various_info.rb

class HotelVariousInfo < ApplicationRecord belongs_to :hotels end

And this is my congresses' controller :

  # POST /congresses
  def create
    @congress = Congress.new(congress_params)
    hotels_params.each do |hotel_param|
      @congress.hotels.new(hotel_param)
      p '>>'
      p hotel_info_params
      p '<<'
      hotel_info_params.each do |hotel_info_param|
        @congress.hotels.hotel_various_infos.new(hotel_info_param)
      end
    end


    if @congress.save
      render json: @congress, status: :created, location: @congress
    else
      render json: @congress.errors, status: :unprocessable_entity
    end
  end


  # Only allow a trusted parameter "white list" through.
  def congress_params
    params.require(:congress).permit(
        :name,
        :subtitle,
        :place,
        :date_from,
        :date_to,
        :host_company,
        :host_logo_url,
        :color,
        :template_id,
        :hotels,
        :hotel_various_infos
    )
  end

  def hotels_params
    params.permit(
        hotels: [:name,
                 :address,
                 :postal_code,
                 :city, :country,
                 :phone_nbr,
                 :check_in_time,
                 :check_out_time
        ]
    ).require(:hotels)
  end

  def hotel_info_params
    params.permit(hotel_various_infos: [:title, :content]).require(:hotel_various_infos)
  end

I'm not sure about my usage of strong parameters.

I get a "exception": "#", when calling this route.

Congres and its hotel are perfectly handled when "hotel_various_info" handling is removed.

When I call /congresses/{ID} I get the congres, hotels, and hotel_various_informations without any problem.

Thanks for your help.

mardi 1 novembre 2016

how to post checkboxes array based on check and uncheck checkboxes ruby on rails

I have array of checkboxes from which I need to store data row by row in the database.

Scenario is if user mark checkboxes the database should store value of is_present check as true and the information of that respective user as well.

If user mark uncheck, the database should store value of is_present check as false and the information of that respective user as well.

My main issue is I am unable to post both true and false at a time. I am only having true in params but unable to get false and its respective user information.

Also I am unable to see true or false belongs to which user in params.

I am also trying fields_for with it.

also how I can store them as row by row in database from params?

So, final words are, I have attendance table in which in the start there are no records but I am showing student registrations from some other table and I wants to tick or untick users from registrations table and have this information store in attendance table.

If tick marked then is_present as true and information of that user, if tick unmarked then is_present as false and information of that user.

The checkboxes could be 100+ so I created array of checkboxes.

Here is my code:

<%= form_for ([:teacher, @teacher, @class_room, @subject, @lesson, @attendance]) do |f| %>
          <table id class="table table-bordered table-sm">
            <thead>
            <tr>
              <th width="30%">Mark Attendance</th>
              <th width="30%">Student</th>
              <th width="30%">Grades</th>
            </tr>
            </thead>
            <tbody id="class_room_attendances">
            <% @class_room_registrations.each do |class_room_registration| %>
                <tr>
                  <td>
                    <%= f.check_box "is_present", {}, true, false %>
                    <label>Check / Uncheck To Mark Attendance</label>
                  </td>
                  <%= f.fields_for :class_room_registrations, class_room_registration do |class_room_registration_fields| %>
                      <%= class_room_registration_fields.hidden_field :user_id, value: class_room_registration.user_id %>
                      <%= class_room_registration_fields.hidden_field :student_id, value: class_room_registration.student_id %>
                  <% end %>
                </tr>
            <% end %>

            </tbody>
          </table>
          <div class="form-group">
            <%= submit_tag 'Mark Attendance', class: 'btn btn-lg btn-info' %>
          </div>
      <% end %>

Create code:

def create
    @attendance = @lesson.attendances.new(attendance_params)
    flash[:notice] = "Attendance marked successfully"
    respond_to do |format|
      if @attendance.save
        format.html { redirect_to teacher_teacher_class_room_subject_lessons_path(@teacher, @class_room, @subject) }
        format.json { head :no_content }
        format.js
      end
    end
  end

Params are:

{"utf8"=>"✓", 
"authenticity_token"=>"dy3eO7sNEBM+NV0Wwu08l/cIfoJp2VRJr06VW9B75K8Ru8s+q367vna
PK+6sCOxN1ICfcUYhLUaZ71HRI71C5g==", "attendance"=>{"is_present"=>"true", 
"class_room_registrations"=>{"user_id"=>"5", "student_id"=>"1"}}, 
"commit"=>"Mark Attendance", "controller"=>"teacher/attendances", 
"action"=>"create", "teacher_id"=>"delfina-kozey", "class_room_id"=>"15", 
"subject_id"=>"4", "lesson_id"=>"25"}

Generated HTML:

<form class="new_attendance" id="new_attendance" action="/teacher/delfina-kozey/class_rooms/15/subjects/4/lessons/25/attendances" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="E2hKfNCGUePkmp5TLfr43rYW/3RP6znEekYHjxs5dMJ1/l95wPX6Tqwg6KtDHygElZ4eh2ATQMtM58MF6P/Siw==">
          <table id="" class="table table-bordered table-sm">
            <thead>
            <tr>
              <th width="30%">Mark Attendance</th>
            </tr>
            </thead>
            <tbody id="class_room_attendances">
                <tr>
                  <td>
                    <input type="checkbox" value="true" checked="checked" name="attendance[is_present]" id="attendance_is_present">
                    <label>Check / Uncheck To Mark Attendance</label>
                  </td>

                      <input value="6" type="hidden" name="attendance[class_room_registrations][user_id]" id="attendance_class_room_registrations_user_id">
                      <input value="2" type="hidden" name="attendance[class_room_registrations][student_id]" id="attendance_class_room_registrations_student_id">
                </tr>
                <tr>
                  <td>
                    <input type="checkbox" value="true" checked="checked" name="attendance[is_present]" id="attendance_is_present">
                    <label>Check / Uncheck To Mark Attendance</label>
                  </td>

                      <input value="5" type="hidden" name="attendance[class_room_registrations][user_id]" id="attendance_class_room_registrations_user_id">
                      <input value="1" type="hidden" name="attendance[class_room_registrations][student_id]" id="attendance_class_room_registrations_student_id">
                </tr>

            </tbody>
          </table>
          <div class="form-group">
            <input type="submit" name="commit" value="Mark Attendance" class="btn btn-lg btn-info">
          </div>
</form>

Form Screenshot:

enter image description here

Date/Time selection does is cut off

Rails 3.2

I am using bootstrap-datetimepicker.js

I have the defaults set to:

$.fn.datetimepicker.defaults = {
  maskInput: false,
  pickDate: true,
  pickTime: true,
  pick12HourFormat: false,
  pickSeconds: true,
  startDate: new Date(),
  endDate: Infinity,
  orientation: "auto",
  collapse: true
};

But when I try to pick date/time, if the form is at the bottom of the screen, it's cut off.

enter image description here

I set the orientation to "auto", and I understand that this is supposed to fix the problem, but it's not. Any suggestions?