mardi 30 avril 2019

How to trigger different links to pages for different roles?

I am developing a website for different characters(or Roles) to use by using Ruby on Rails. Ruby: 2.6.0, Rails:5.2.2, Devise.
I want to create a webpage to show different country names. In 'index' page, it will show 'France', 'Switzerland' and 'China'. For different characters(or Roles), they have different permissions, ex: "Global Manager" can click 'France', 'Switzerland', 'China'; "Asia Manager" can only click 'China', and show 'No Permission!' if clicking 'France' or 'Switzerland'.

What I am trying now is using 'if...elsif...else' in 'index.html.erb' and 'countrycheck.html' with conditions of different email address domain. The problem I met is: I login in as 'test01@france.com'(Global Manager). I can see three countries' names in index page(correct), but I get the same page for 'France' title no matter which country I click. I know the error is because in my code 'france.com' matches 'France' page.

How to modify the codes? Is there any better way to realize the functionality? Thanks!

'Index.html.erb'

   <% if current_user.email.split("@").last == "france.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "France", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.email.split("@").last == "switzerland.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "Switzerland", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.email.split("@").last == "china.com" && current_user.character != "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "China", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
            <% elsif current_user.character == "Global Manager"%>
                 <br>
                 <br>
                 <li><%= link_to "France", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
                 <br>
                 <br>
                 <li><%= link_to "Switzerland", "http://localhost:3000/countrycheck.html", :class => "choices" %></li>
                 <br>
                 <br>
                 <li><%= link_to "China", "http://localhost:3000/maisoncheck.html", :class => "choices" %></li>
            <% else %>
                 <br>
                 <br>
                 <li><%= link_to "Other Countries", "http://localhost:3000/maisoncheck.html", :class => "choices" %></li>
            <% end %>

'countrycheck.html.erb'

<% if current_user.email.split("@").last == "france.com" %>
            <h1><%= link_to "France", "#"%></h1>
        <iframe>some iframe information related to France</iframe>
        <% elsif current_user.email.split("@").last == "switzerland.com" %>
            <h1><%= link_to "Switzerland", "#"%></h1>
        <iframe>some iframe information related to Swizterland</iframe>
        <% elsif current_user.email.split("@").last == "china.com" %>
            <h1><%= link_to "China", "#"%></h1>
       <iframe>some iframe information related to China</iframe>
        <% else %>
                <iframe> other countries iframe information </iframe>
        <% end %>

country_controller.rb

class CountryController < ApplicationController

    before_action :authenticate_user!
    before_action :check_admin

    def index
        @users = User.all
    end

    def show
        @users = User.all
    end

    def countrycheck
        if current_user
        else
            flash[:alert] = "No permission!"
            redirect_to "http://localhost:3000/country.html"
        end
    end

    protected

    def check_admin
        unless current_user.character == "Global Manager" || "Regional Manager"
          flash[:alert] = "No permission!"
          redirect_to "http://localhost:3000/introduction.html"
         return
        end
    end
end

lundi 29 avril 2019

ActionController::UrlGenerationError in Interfaces#index

I am trying to delete my interface,and it said No route matches {:action=>"show", :controller=>"interfaces", :project_id=>#}, missing required keys: [:id].

Because I do not which arguments should be put into <%=link_to '删除', project_interface_path()%>

I have tried many different arguments into a path.

It is my interface_controller.rb file:

def destroy
    @interface = @proeject.interfaces.find(params[:project_id])
    if @interface.destroy
      redirect_to project_interfaces_path
    end
end
  def index
    @interfaces = Interface.all
    @project = Project.find(params[:project_id])

  end
  def new
    @project = Project.find(params[:project_id])
    @interface = Interface.new
  end

  def create
    @project = Project.find(params[:project_id])
    @interface = @project.interfaces.new(interface_params)
    if @interface.save
      redirect_to project_interfaces_path
    else
      render :new
    end
  end
 It is my interface/index.html.erb

 <% @interfaces.each do |interface| %>
      <tr>
        <th scope="row">1</th>
        <td><%=interface.name %></td>
        <td><%=interface.desp %></td>
        <td><%=interface.method_type_id %></td>
        <td><%=interface.request_url %></td>
        <td><%=interface.request_eg %></td>
        <td><%=interface.response_eg %></td>
      </tr>
      <td><%= link_to '删除', project_interface_path(interface),method: :delete, data:{confirm:'确定要删除吗?'}, class: 'badge badge-dark' %></td>

dimanche 28 avril 2019

Is there any way to combine similar html.erb file in views & actions in controller?

I am building a website by using ruby on rails. There is a country list. By clicking different country names , it will link to webs which show information related to this country. These webs are quite similar. Even more, people only have permission to country which they come from. Now, I create several html.erb files under 'views'->'country' folder, and several actions in 'Country' controller. It works, but I want to make codes more efficient. Is there any way to combine these similar html.erb files into one html.erb file and combine actions to one action in controller? Use 'if...else...'? Any suggestions are welcome and thankful.

enter image description here

   class CountryController < ApplicationController
before_action :authenticate_user!
before_action :check_admin

def index
    @users = User.all
end

def show
    @users = User.all
end

def france
    unless current_user.email == "test@france.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

def switzerland
    unless current_user.email == "test@switzerland.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

def china
    unless current_user.email == "test@china.com"
        flash[:alert] = "No permission!"
        redirect_to "http://localhost:3000/country.html"    
    end
end

protected
    end

expected result: combine similar html.erb files into one html.erb file and combine actions to one action in controller

vendredi 26 avril 2019

Rails (Object doesn't support #inspect) / NoMethodError (undefined method `[]' for nil:NilClass)

I have a model "Section". Whenever I try to iterate over Section object, like, "Section.all" or "Section.create", I get error as "(Object doesn't support #inspect)" in rails console and "NoMethodError (undefined method `[]' for nil:NilClass)" in the terminal.

I really need some help since it has become a road blocker.

Ruby : ruby 2.6.1p33

Rails : 5.2.3

Section migration

class CreateSections < ActiveRecord::Migration[5.2]
  def change
    create_table :sections do |t|
      t.string :name
      t.integer :students_count, :default => 0
      t.references :class, index: true
      t.references :class_teacher, index: true

      t.timestamps
    end
    add_foreign_key :sections, :standards, column: :class_id
    add_foreign_key :sections, :users, column: :class_teacher_id
  end
end

Section model

class Section < ApplicationRecord
  belongs_to :class, :class_name => "Standard", :foreign_key => "standard_id"
  belongs_to :class_teacher, :class_name => "User", :foreign_key => "class_teacher_id"
end

Controller code

def index
  @sections = Section.where(:class_id => params[:class_id])

  render json: @sections
end

Terminal output

NoMethodError (undefined method `[]' for nil:NilClass):

Rails console Input

Section.all

Rails console output

(Object doesn't support #inspect)

Strangely, when Section table is empty, console output is

#<ActiveRecord::Relation []> 

Thanks in advance.

jeudi 25 avril 2019

Polyline straight instead of snapping to road on Ruby app

I have added the following code to display a map and draw a path on it. There could be many points to display (So start, waypoints and end). The points are all in a table Location which has both latitude and longitude fields. I am not sure how to pass the information so that the table shows up and the path connected the different stops

<script>
    var map_options = {
        center: new google.maps.LatLng('<%= current_user.latitude %>', '<%= current_user.longitude %>'),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        mapTypeControl: false,
        zoomControlOptions: { position: google.maps.ControlPosition.LEFT_CENTER }
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"), map_options);
    var apiKey = '<%= Rails.application.secrets.google_secret%>';

    function processSnapToRoadResponse(data) {
        snappedCoordinates = [];
        placeIdArray = [];
        for (var i = 0; i < data.snappedPoints.length; i++) {
            var latlng = new google.maps.LatLng(
                data.snappedPoints[i].location.latitude,
                data.snappedPoints[i].location.longitude);
            snappedCoordinates.push(latlng);
            placeIdArray.push(data.snappedPoints[i].placeId);
        }
    }

    function drawSnappedPolyline() {
        var snappedPolyline = new google.maps.Polyline({
            path: snappedCoordinates,
            strokeColor: 'black',
            strokeWeight: 3
        });

        snappedPolyline.setMap(map);
        polylines.push(snappedPolyline);
    }



    function runSnapToRoad(path) {
        var pathValues = [];
        for (var i = 0; i < path.getLength(); i++) {
            pathValues.push('???????????????????');
        }

        $.get('https://roads.googleapis.com/v1/snapToRoads', {
            interpolate: true,
            key: apiKey,
            path: pathValues.join('|')
        }, function(data) {
            processSnapToRoadResponse(data);
            drawSnappedPolyline();
        });
    }






</script>

Does anybody knows how to pass the array of longitude/latitude? I have checked the following links: http://www.kadrmasconcepts.com/blog/2013/06/28/drawing-polylines-with-rails-and-google-maps/ This one does not show how he gets the path, as a result when using his path it is fine, but when creating my own path, I get a straight line.

https://developers.google.com/maps/documentation/roads/snap This is the current code that I used.

Call windows exe file from rails application

I am calling exe file from rails application.I have set-up rails application over windows machine and from code I am running exe file.In this I need to pass a path in the arguments.

@project = Project.find(params[:project_id])
xml_file_path = @project.xml_file_name
basename = File.basename(xml_file_path) i.e "12.xml"

Tried this -

final_xml_path = "C:\Windows\System32\workspace\preference\public\xml_files\#{basename}"

I have tried this -

 final_xml_path = 'C:\\Windows\\System32\\workspace\\preference\\public\\xml_files\\#{basename}'

Output - p final_xml_path

"C:\\Windows\\System32\\workspace\\preference\\public\\xml_files\\\#{basename}" 

Desired output -

final_xml_path = "C:\Windows\System32\workspace\preference\public\xml_files\12.xml"

I need this output I need to pass in the arguments while running exe file.

mercredi 24 avril 2019

ArgumentError in StaticPages

I had a working pagination but after some changes to the gemfile, all the pagination started throwing this error wrong number of arguments (given 0, expected 1)

The gemfile changes have brought the errors on every class that needs pagination so it could be an issue about how I am handling the gem. The error is here Showing /home/ec2-user/environment/homework_helper/app/views/assignments/assignment/_homework_answers_page.html.erb where line #3 raised:

  <%= will_paginate @assignments  %> -line  3


      <% @assignments.each do | assignment | %>

      <tr>


gem 'will_paginate',           '3.1.6'
gem 'will_paginate-bootstrap4'


 def homework_answers
   @assignment = Assignment.new
   @categories = Category.all
   @assignments = Assignment.all
   @assignments =  Assignment.paginate(page: params[:page], per_page: 10)
  end