mardi 13 juin 2017

How can I create ActiveRecord for the following sql

How can I create an ActiveRecord Query for the following Sql query

SELECT device1.*
FROM devices device1
WHERE device1.id = (SELECT MAX(device2.id)
                 FROM devices device2
                 WHERE device2.user_id = device1.user_id);

I have Device model with user_id column

I dont want to user find_by_sql because it returns Array instead ActiveRecord Array

How to validate email is real or fake in Rails?

I have a problem I need write validator in rails to checking an email is real or fake? I try to research but nothing. Can someone help me? Thanks !

lundi 12 juin 2017

My User_id is updated to nil every time I refresh my page in Rails

I know what is causing this issue, but can't find the working alternative of it. I will describe the problem and hope for a good answer.

So, I have a bootstrap modal in which i have a form. that form _for is calling GalleryController#create method.. this is my modal -->

#gallery_create_modal.modal.fade.m{'tabindex':-1 , 'role':'dialog','aria-labelledby':'creategallery'}
    .modal-dialog.modal-lg{'role':'document'}
        .modal-content
            =form_for @gallery , html: {multipart: true}  do |f|

                ...content

                =f.submit 'Upload' , class: 'btn btn-primary'           

and here is my gallery controller

class GalleriesController < ApplicationController

before_action :authenticate_amitian!

def create
@gallery = current_amitian.create_gallery(gallery_params)

end

private

def gallery_params
params.require(:gallery).permit(:g1,:g2,:g3,:g4,:g5,:g6,:amitian_id)
end

end

upto this point if I run the code it returns error saying first element of form can't be empty or nil... means my @gallery is nil

this is because my modal is in my Amitians#show page so to solve this I had to initialize my @gallery inside Amtians#show method like this -->

class AmitiansController < ApplicationController

before_action :authenticate_amitian!, except: [:show]

def index
...content
end

def show
....
@gallery = current_amitian.build_gallery
....

end

This takes away the error but everytime I refresh my page after upload.. it updates my sql table's Gallery.amitian_id to NULL

I can't seem to find a sol. please help. Thank you.

Getting all users from db that participated for an activity

I am currently facing the following problem: Users are able to create activities. Other users have the possibility, to participate the activity. I now want that the users, which already participated to an activity are going to be listed in the view of the activity. So what I try is to show all the users that participated for an activity in the show method of the activity_controller with an activity_id.

The relations of the models are as follows:

 class Activity < ActiveRecord::Base
  has_many :users, through: :participations
  belongs_to :user
  has_many :participations
  has_many :reviews

end


 class Participation < ActiveRecord::Base
  belongs_to :user
  belongs_to :activity
  has_many :activities
end




 class User < ActiveRecord::Base
  has_many :activities
  has_many :participations
  has_many :reviews

end

My activity controller ist doing the following:

class ActivitiesController < ApplicationController
  before_action :set_activity, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show]

  def index
    @activities = Activity.all
  end

  def show
    @participated = Participation.where("activity_id = ? AND user_id = ?", @activity.id, current_user.id).present? if current_user
    @reviews = @activity.reviews
    @hasReview = @reviews.find_by(user_id: current_user.id) if current_user

    @participant = Participation.where (:activity_id == 'activity_id')
  end



  def new
    @activity = current_user.activities.build
  end

  def create
    @activity = current_user.activities.build(activity_params)

    if @activity.save

      redirect_to edit_activity_path(@activity), notice: "We want to give you a warm welcome!"

    else
      render :new, notice: "Something seems to be missing!"
    end
  end

  def edit
    if current_user.id == @activity.user.id
      redirect_to root_path
    end
  end

  def update
    if @activity.update(activity_params)
      redirect_to edit_activity_path(@activity), notice: "Updated!"
    else
      render :edit
    end
  end

  def destroy
    @activity = Activity.find(params[:id])

    if @activity.destroy
      redirect_to activities_path, notice: "Deleted!"
    end
  end

  private

  def set_activity
    @activity = Activity.find(params[:id])
  end


  def activity_params
    params.require(:activity).permit(:activity_name,
                                     :activity_starttime,
                                     :activity_duration,
                                     :activity_intensity,
                                     :activity_distance,
                                     :activity_topography,
                                     :activity_address,
                                     :activity_track,
                                     :activity_summary)

  end
end

Meanwhile the participations controller handles this:

    class ParticipationsController < ApplicationController
  before_action :authenticate_user!

  def preload
    activity= Activity.find(params[:activity_id])
    participations = activity.participations
    render json: participations
  end

  def create

    if Participation.exists?(user_id: current_user.id)

      redirect_to activities_path(@activity), notice: "Du nimmst bereits teil!"

    else

      @participation = current_user.participations.create(participation_params)
      redirect_to @participation.activity, notice: "Klasse, du nimmst nun teil!"

    end

  end


  def participant
    @participant = user.participations
  end

  def your_matches
    @matches = current_user.participations
  end

  def your_participations
    @activities = current_user.activities
  end

  private

  def participation_params
    params.permit(:activity_id, :status)
  end
end

In my view, I called the controller by using:

<div class="row">
  <div class="col-md-12">
    <h3>Wer kommt bis jetzt mit? </h3>


    <table>
      <tr>
        <th></th>
      </tr>

      <% @participant.each do |participant| %>

          <tr>
            <td><%= participant.user.fullname %></td>
          </tr>

      <% end %>

    </table>

  </div>
</div>

Which gives me a list of all users that participated for any activity. But the only thing I want now is to show all the users which participated for the activity requested. I would say that my relations should work properly, therefore I guess I just need a small hint to solve the problem. At another point of my app I already got a list, where I am able to show the users which participated, but because of the different controllers, I am not able to call this from the activity controller. All in all, this causes an error because I am not able to call the participations_controller from an activitities_view.

<div class="panel-body">
    <% @activities.each do |activity| %>
      <% activity.participations.each do |participation| %>


      <div class="row">

        <div class="col-md-3">
          <%= link_to user_path(participation.user) do %>
              <%= participation.user.fullname %>
          <% end %>
      </div>

Would really appreciate any help and thanks in advance!

dimanche 11 juin 2017

Subscription class not found 'MyChannel' in ActionCable

I am facing a problem while working with Action Cable, whenever I run my program I receive an error that says 'Subscription Class not found 'ConversationChannel'

and when I try to send a message I get this log

    Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Subscription class not found: "ConversationChannel"
Could not execute command from {"command"=>"message", "identifier"=>"{\"channel\":\"ConversationChannel\"}", "data"=>"{\"message\":[{\"name\":\"conversation_id\",\"value\":\"2\"},{\"name\":\"amitian_id\",\"value\":\"1\"},{\"name\":\"body\",\"value\":\"nmm\"}],\"action\":\"speak\"}"}) [RuntimeError - Unable to find subscription with identifier: {"channel":"ConversationChannel"}]: C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:74:in `find' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:53:in `perform_action' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:17:in `execute_command' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/server/worker.rb:58:in `block in invoke'

I will give my channel.rb and other js files

Here is my ConversationChannel.rb

       class ConversationChannel < ApplicationCable::Channel
      def subscribed
        # stream_from "some_channel"
        stream_from "conversations-#{current_amitian.id}"
      end

      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
        stop_all_streams
      end

      def speak(data)

        message_params = data['message'].each_with_object({}) do |el, hash|
          hash[el.values.first] = el.values.last
        end

        ActionCable.server.broadcast(
          "conversations-#{current_amitian.id}",
          message: message_params
        )
      end

     end

Here is my conversation.js

    App.conversation = App.cable.subscriptions.create("ConversationChannel", {
  connected: function() {

  },
  disconnected: function() {

  },
  received: function(data) {
  console.log(data['message']);
  },
  speak: function(message) {
    return this.perform('speak' , {
    message: message
    });
  }
});

$(document).on('submit', '.new_message', function(e) {
  e.preventDefault();
  var values = $(this).serializeArray();
  App.conversation.speak(values);
  $(this).trigger('reset');
});

This is my connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_amitian

    def connect
        self.current_amitian = find_verified_amitian
    end

    protected

    def find_verified_amitian
        if(current_amitian = env['warden'].amitian)
            current_amitian
        else
            reject_unauthorized_connection
        end
    end
  end
end

using the log file given above can anyone tell me why It can't find my conversation_channel.rb file ?

Thank you

I Want to develop web application that monitors and extract inforamtion from linux servers. How to begin with Ruby or Python

Learning programming on my own, need some guidance on best platform/tool/language and libraries to build application my own application that monitors, sends and pulls out information (i.e. server logs, data from monitoring tools) from multiple linux servers. ideally i want a client program that keeps pushing the data to sever from where i can show on the web interface.

Rails refuse to generate new controller

Hi everyone and thanks for the great work. I have a problem with rails : I created a fresh app nicely running on port 3000. I'm trying to reate a nw controller using "rails generate controller Welcome index" and rails is throwing this :

Ignoring bindex-0.5.0 because its extensions are not built.  Try: gem pristine bindex --version 0.5.0
/usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find nokogiri-1.8.0 in any of the sources (Bundler::GemNotFound)
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:81:in `map!'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:81:in `materialize'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:159:in `specs'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:218:in `specs_for'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:207:in `requested_specs'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/runtime.rb:109:in `block in definition_method'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/runtime.rb:21:in `setup'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler.rb:101:in `setup'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/setup.rb:20:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/commands.rb:33:in `<module:Spring>'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/commands.rb:4:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/server.rb:9:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client/server.rb:9:in `call'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client.rb:30:in `run'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/bin/spring:49:in `<main>'

Does someone have an idea of what this could be ? I cannot figure it out and I will appreciate any help. My OS is opensuse tumbleweed.

Thanks.