Saturday, August 13, 2016

rails passes json to javascript file, But javascript shows error | Fixed issues

rails passes json to javascript file, But javascript shows error | Fixed issues


rails passes json to javascript file, But javascript shows error

Posted: 13 Aug 2016 08:29 AM PDT

So i've got a rails call, It works lovely and passes this into postman (shortened because its huge)

SEEvent({"event_id":"ID","date":"Sat 20 Aug 2016, 10:00","suppress_best_available":"","sorted_ticket_types":["000000000001"],"is_resale_eligible":0,"ada_tickets_enabled":0,"suppress_any_price":"","expand_resale_module_ntf":1,"expand_resale_module":"","bba_deep_links_offer_code":  

For some reason when i try and call it in my javascript file (which looks like this):

$.ajax({    type: 'GET',    crossDomain: true,    dataType: 'json',    url: '/event/'+ event,    success: function(json) {      debugger;  

The error function is shown instead of the success. In the debugger, i have response code 4 and in the response text is all the json i need.

Any help would be amazing

I've tried changing the dataType to jsonp which also didnt work.

Sam

Unable to access related properties on ActiveRecord query

Posted: 13 Aug 2016 07:37 AM PDT

I'm not entirely sure if I have my relationships set up correctly, but here's what I'm trying to do. I'm trying to return the Grade for a Students active Enrollment.

current_enrollments = self.enrollments.where('admission_date <= ? and withdraw_date is null or withdraw_date >= ?', Date.today, Date.today)    class SchoolYearGrade < ApplicationRecord    belongs_to :school_year    belongs_to :grade    has_many :enrollments  end    class Enrollment < ApplicationRecord    belongs_to :student    belongs_to :school_year_grade  end    class Grade < ApplicationRecord    has_many :school_years, through: :school_year_grades    has_many :school_year_grades  end    class Student < ApplicationRecord        has_many :enrollments      def get_current_grade      if self.enrollments.any?        current_enrollments = self.enrollments.where('admission_date <= ? and withdraw_date is null or withdraw_date >= ?', Date.today, Date.today)        if current_enrollments.count == 1          current_enrollments.first.school_year_grade.grade.title        else          ...        end      else        ...      end    end  end  

When debugging in the get_current_grade method in the Student model, I try to access current_enrollments.first.school_year_grade.grade and only Nil is returned. I then tried adding .includes(:school_year_grade) to the query on current_enrollments, but I still wasn't able to get anything.

How can I hide activities with no user?

Posted: 13 Aug 2016 07:20 AM PDT

I'm trying to hide activities where their owners have deleted their accounts. So I added this

PublicActivity::Activity.order("created_at DESC").where( recipient: current_user).where.not(owner: nil)  

but it returns

undefined method `image' for nil:NilClass  

meaning it's adding activities with deleted users to the record. How can I hide them?

How to give different access levels to admins in Active Admin:Rails?

Posted: 13 Aug 2016 07:18 AM PDT

I have added a attribute to admin user, which is called hostel_name. now the Hostel is a upper most model in hierarchy and contains just only one attribute which is hostel_name(same as active admin model) ,means all models are related to that model somehow. now I want the active admins to view just only there hostel's data... !! How can I do that thing in active admin Help plz.

One Model without nested Form Rails

Posted: 13 Aug 2016 08:05 AM PDT

I have only one user model, I want to give add more option on the form. There are many example have nested form but in my case no need to nested because I have only one user model. I want to save bulk of users using add more form

Search for an object in rails by an array and create objects if not exist

Posted: 13 Aug 2016 06:44 AM PDT

I want to call the ActiveRecord method where with an array for a column. If the each item on the array doesn't exist, create the object. The closest method I found for this is first_or_create but this seems to be called only once, not for each time the record doesn't exist. Below is my example code-

hashtag_list = params[:message][:hashtag_primary]  @hashtags = Hashtag.where({:name => hashtag_list}).first_or_create do |hashtag|     hashtag.creator = current_user.id  end  

Rails version- 4.2.1

Docker Rails app with searchkick/elasticsearch

Posted: 13 Aug 2016 06:17 AM PDT

Im porting my rails app from my local machine into a docker container and running into an issue with elasticsearch/searchkick. I can get it working temporarily but Im wondering if there is a better way. So basically the port for elasticsearch isnt matching up with the default localhost:9200 that searchkick uses. Now I have used "docker inspect" on the elasticsearch container and got the actual IP and then set the ENV['ELASTICSEARCH_URL'] variable like the searchkick docs say and it works. The problem Im having is that is a pain if I restart/change the containers the IP changes sometimes and I have to go through the whole process again. Here is my docker-compose.yml:

version: '2'  services:    web:      build: .      command: rails server -p 3000 -b '0.0.0.0'      volumes:        - .:/living-recipe      ports:        - '3000:3000'      env_file:        - .env      depends_on:        - postgres        - elasticsearch      postgres:      image: postgres      elasticsearch:      image: elasticsearch  

How do you insert an ActiveRecord object via rails Console?

Posted: 13 Aug 2016 06:18 AM PDT

How may i insert an New Active Record object via Rails console.

How come the show path is undefined in a nested resource?

Posted: 13 Aug 2016 06:16 AM PDT

I doing this for fun to understand nested resources. I did scaffold TodoItem and generated the crud general html views. However the default html view has an error and i cannot figure out why. Below is my code. My data tables:
Users ---> has many ---> TodoLists

TodoLists ------> has many----> Todoitems

My model:

class User < ApplicationRecord    has_one :profile, dependent: :destroy    has_many :todo_lists, dependent: :destroy    has_many :todo_items, through: :todo_lists, source: :todo_items    validates :username, presence: true    has_secure_password    def get_completed_count      self.todo_items.where("completed = ?", true).count    end  end        class TodoList < ApplicationRecord    belongs_to :user    has_many :todo_items, dependent: :destroy    default_scope {order :list_due_date}  end          class TodoItem < ApplicationRecord    belongs_to :todo_list    default_scope {order :due_date }  end  

My View:

/app/views/todo_items/index.html      <p id="notice"><%= notice %></p>    <h1>Todo Items</h1>    <table>    <thead>      <tr>        <th>Title</th>        <th>Due date</th>        <th>Description</th>        <th>Completed</th>        <th colspan="3"></th>      </tr>    </thead>      <tbody>      <% @todo_items.each do |todo_item| %>        <tr>          <td><%= todo_item.title %></td>          <td><%= todo_item.due_date %></td>          <td><%= todo_item.description %></td>          <td><%= todo_item.completed %></td>          <td><%= link_to 'Show', todo_item %></td>          <td><%= link_to 'Edit', edit_todo_item_path(todo_item) %></td>          <td><%= link_to 'Destroy', todo_item, method: :delete, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>    </tbody>  </table>    <br>    <%= link_to 'New Todo Item', new_todo_item_path %>  

Error:

Error i got

Ruby on Rails: What is the convention (is there one?) for creating a model instance programmatically

Posted: 13 Aug 2016 08:08 AM PDT

I have a model: 'event' and it has a controller: 'event_controller'

The event_controller handles the following route: events/:id/complete_event

In the controller, I need to trigger the creation a couple other model objects in the system, which are calculated and not inputted via a web form.

In this case the models to create are:

  1. score (which belongs_to: user and event)
  2. stats (which belongs_to: event)
  3. standing (which belongs_to: user | and is based on the new score/stats object)

What is the convention for this type of model creation for Ruby on Rails?

Is it okay for the event_controller to create these (somewhat unrelated) model objects?

or,

Should the event_controller call into the score_controller, stats_controller and standing_controller?

With the second option, I am concerned that it will not work to dispatch 2-3 routes in a chain to create all the objects in their corresponding controllers but is that is the convention.

In the end, it's ideal to redirect the user back to show_event view, which will display the event and its associated scores and stats objects.

Code for the event_controller method: complete_event

def complete_event    event = Event.find(params[:id])    if event.in_progress?      event.complete!    end    # 1. create score for each user in event.users    # 2. create stats for the event    # 3. update the overall standings for each score (per user)    redirect_to event  end  

As you can see, the event is not being creating on this action, rather the event state is updated to 'complete' this is the trigger to create the associated records.

The commented lines above represent what I need to do after event is complete; I am just not sure that this is where I go ahead and directly create the objects.

E.g. To create score will I have to calculate a lot of data that starts in event, but uses many models to get all the relevant data to create it.

"TypeError: no implicit conversion of nil into String" on HABTM association

Posted: 13 Aug 2016 07:05 AM PDT

I have to deal with this error when I try to associate a record to another one via a HABTM association:

Person.first.communities = Communities.all  

Models and migrations:

class CreatePeople < ActiveRecord::Migration    def change      create_table :people do |t|        t.string :name        t.string :email          t.timestamps null: false      end    end  end     class CreateCommunities < ActiveRecord::Migration     def change       create_table :communities do |t|         t.string :name         t.text :description           t.timestamps null: false       end     end   end    class CreateJoinTablePersonCommunity < ActiveRecord::Migration    def change      create_join_table :people, :communities do |t|        # t.index [:person_id, :community_id]        # t.index [:community_id, :person_id]      end    end  end  

I use the pg (0.18.4) gem with the Postgres (9.5.2)

Rails nested form with multiple check boxes - values not stored in the db

Posted: 13 Aug 2016 05:03 AM PDT

I really need a help here as I am running out of ideas what can be wrong here.

Models

class Rfq < ActiveRecord::Base    belongs_to :purchase    belongs_to :supplier    belongs_to :customtemplate      has_many :rfq_products    accepts_nested_attributes_for :rfq_products, :allow_destroy => true  end    class RfqProduct < ActiveRecord::Base    belongs_to :rfq   end  

Form

<%= simple_form_for @rfq do |f| %>  (...)  <%= f.simple_fields_for :rfq_products do |rfq_product|  %>       <%= rfq_product.check_box :product, { :multiple => true }, 8, nil %>       <%= rfq_product.check_box :product, { :multiple => true }, 9, nil %>  <% end %>  <%= f.button :submit %>  <% end %>  

rfq_controller

def new      @rfq = Rfq.new      @rfq.rfq_products.build  end    def create      @rfq = Rfq.new(rfq_params)        respond_to do |format|        if @rfq.save          #format.html { redirect_to @rfq, notice: 'Rfq was successfully created.' }          format.html { redirect_to :back, notice: 'Rfq was successfully created.' }          format.json { render :show, status: :created, location: @rfq }        else          format.html { render :new }          format.json { render json: @rfq.errors, status: :unprocessable_entity }        end      end    end    def rfq_params    params.require(:rfq).permit(:customtemplate_id, :supplier_id, :purchase_id, :code,         rfq_products_attributes: [ :id, :_destroy, product: [] ])  end  

When I check params that I get after submitting form, I have sth like that:

pry(#<RfqsController>)> rfq_params  => {"supplier_id"=>"7", "purchase_id"=>"4", "rfq_products_attributes"=>{"0"=>{"product"=>["8", "9"]}}}  

and in the inserts that are genertaed, value of the products is omitted (they are not stored in the db). I do not get error that any value in the params is not permitted.

(3.1ms)  BEGIN    SQL (1.1ms)  INSERT INTO "rfqs" ("supplier_id", "purchase_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["supplier_id", 7], ["purchase_id", 4], ["created_at", "2016-08-13 11:50:49.460475"], ["updated_at", "2016-08-13 11:50:49.460475"]]    SQL (3.8ms)  INSERT INTO "rfq_products" ("rfq_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["rfq_id", 42], ["created_at", "2016-08-13 11:50:49.505250"], ["updated_at", "2016-08-13 11:50:49.505250"]]     (39.0ms)  COMMIT  

So what can cause that problem?

Rails Pundit Policy Spec test failing with NoMethodError

Posted: 13 Aug 2016 07:21 AM PDT

I have just started using Pundit for authorization in my current project along with the pundit_matchers gem.

So far it seems to generally be working for me but I have a problem in my tests.

I have generally tried to follow the examples in the pundit_matcher readme and the Thunderbolt labs blog (http://thunderboltlabs.com/blog/2013/03/27/testing-pundit-policies-with-rspec/).

This is my policy file;

#app/policies/procedure_policy.rb  class   ProcedurePolicy      attr_reader :user, :procedure        def initialize(user, procedure)          @user = user          @procedure = procedure      end        def index?          user.admin?      end    end  

And this is my policy_spec file

require 'rails_helper'    describe ProcedurePolicy do      subject {described_class.new(user, procedure)}        let(:procedure) {FactoryGirl.create(:procedure)}        context "for a guest" do          let(:user) {nil}          it {is_expected.not_to permit_action(:index)}      end        context "for a non-admin user" do          let(:user) {FactoryGirl.create(:user)}          it {is_expected.not_to permit_action(:index)}      end        context "for an admin user" do          let(:user) {FactoryGirl.create(:admin_user)}          it {is_expected.to permit_action(:index)}      end    end  

2 of my 3 tests pass; The "for a non-admin user" and "for an admin user" ones. The "for a guest" test fails with

NoMethodError:         undefined method `admin?' for nil:NilClass  

Now I understand why. I'm passing nil to the #index? method of my ProcedurePolicy class which will not have an #admin? method. But all of the example specs I have found online do exactly this. What am I not seeing.

Apologies if I'm missing something really obvious. I've been away from coding for a couple of years.

ActionView::Template::Error (undefined method `protect_against_forgery?' for #<#<Class:0x85f1220>:0x85fa808>):

Posted: 13 Aug 2016 03:37 AM PDT

I am using devise gem in an api service got the error

I have searched but not helpfull

undefined method `protect_against_forgery?' for #<#<Class:0x0

I did

class UsersSessionsController < Devise::SessionsController      before_action :resource    before_action :resource_name    before_action :devise_mapping    before_action :protect_against_forgery?      def new      super    end      def create      super    end      def resource_name      :user    end      def resource      @resource ||= User.new    end      def devise_mapping      @devise_mapping ||= Devise.mappings[:user]    end      def protect_against_forgery?      true    end  end  

then routes

  devise_for :users, :controllers => {:sessions => "users_sessions"}    resources :users_sessions  

also generate views in locally.

Please help

I also see

https://github.com/plataformatec/devise/issues/4003

My view

Log in

<%= form_for(:user, url: new_users_session_path) do |f| %>    <div class="field">      <%= f.label :email %><br />      <%= f.email_field :email, autofocus: true %>    </div>      <div class="field">      <%= f.label :password %><br />      <%= f.password_field :password, autocomplete: "off" %>    </div>      <%# if devise_mapping.rememberable? -%>      <div class="field">        <%= f.check_box :remember_me %>        <%= f.label :remember_me %>      </div>    <%# end -%>      <div class="actions">      <%= f.submit "Log in" %>    </div>  <% end %>  

Add additional folders like public on rails application

Posted: 13 Aug 2016 03:02 AM PDT

I'm trying to display some static landing pages on my client's rails application. Till now I'm putting all the content inside the my_app/public/website folder and mapping routes like

match '', :to => redirect('/website/index.html')  

and on clicking signin/signup user will get redirect to rails application. Now He is asking me to move folder like my_app/website.

I've changed folder structure as above and change routes as

match '', :to => redirect('website/index.html')  

and I'm getting this error

ERROR URI::InvalidURIError: the scheme http does not accept registry part  

This was just the hit and trial appoach and to be honest with you I'm not sure if it is possible to do so.

Many thanks

Any suggestions will be appreciated.

Event turbolinks:load working strange

Posted: 13 Aug 2016 04:03 AM PDT

Please help my. I use rails5 with gem turbolinks. My navigation menu code:

<div id="templatemo_menu" class="ddsmoothmenu">      <ul>        <li><a class="level_0 index" href="/">Главная</a></li>          <li><a class="level_0 about" href="/pages/about">О нас</a></li>          <li><a class="level_0 portfolio" href="/type_works">Портфолио</a>          <ul>              <li><a class="level_1" href="/works?type_work_id=1">Corporate Metrics Liaison</a></li>              <li><a class="level_1" href="/works?type_work_id=2">Chief Solutions Planner</a></li>              <li><a class="level_1" href="/works?type_work_id=3">Central Applications Architect</a></li>              <li><a class="level_1" href="/works?type_work_id=4">Global Metrics Executive</a></li>          </ul>        </li>          <li><a class="level_0 blog" href="/blog_articles">Блог</a></li>          <li><a class="level_0 contact" href="/contact_messages/new">Контакт</a></li>      </ul>        <br style="clear: left">    </div>  

I need to after clicking on the '.about', BODY background changed to red. But now after clicking BODY background not changed. Its problem.

My attempt to solve:

var menuActivePunkt = function(){     var pathname = location.pathname,      pathnameList = pathname.split('/'),      slug1 = pathnameList[1],      slug2 = pathnameList[2];      console.log('slug1', slug1);    console.log('slug2', slug2);      $('#templatemo_menu a').removeClass('selected').on('click', function() {      if(slug1 == 'pages' && slug2 == 'about') {        //$('.index').addClass('selected');        $('body').css({'background': 'red'});      };    });  }      $( document ).on('turbolinks:load', function() {    menuActivePunkt();  })  

Ruby on Rails : Blocks, Methods, Control Flows not working

Posted: 13 Aug 2016 03:27 AM PDT

I'm a newbie in Ruby on Rails, but I've been coding for quite some time on other platforms as C# etc. Problem I'm facing is: Whenever I tried to do any thing in blocks, methods, or control flows it gives me error:

syntax error, unexpected ')', expecting ';' or '\n' ....append=( def createFormTable );@output_buffer.safe_append=' ... ^
new.html.erb:5: syntax error, unexpected keyword_end ...eze;@output_buffer.append=( end );@output_buffer.safe_append...
new.html.erb:6: syntax error, unexpected keyword_end ...eze;@output_buffer.append=( end );@output_buffer.safe_append...
new.html.erb:9: syntax error, unexpected keyword_ensure, expecting ')'
new.html.erb:11: syntax error, unexpected keyword_end, expecting ')'

My Code

<%= form_for @contact do |f| %>        <%= f.label :name %>      <%= f.text_field :name %>        <%= f.label :email %>      <%= f.email_field :email %>        <%= f.label :comments %>      <%= f.text_area :comments %>  <%= end %>  

No matter I try the above code or just simple condition/method writing as this:

<%= if 1==1 %>    <%= else %>    <%= end %>  

or this :

<%= def createFormTable %>      <%= form_for @contact do |f| %>      <%= end %>  <%= end %>   

Solutions Tried

Rails: syntax error, unexpected keyword_ensure, expecting $end

rails: syntax error, unexpected keyword_ensure, expecting end-of-input

group :development do   gem 'better_errors'  end  

got above code from one of the answers.

Please help me out with this. I've spent my 5 to 6 hours in this one simple thing. Please direct me to what I'm missing. Thank you everyone in advance.

Rails 4 - jQuery hide/show fields not working in production mode [on hold]

Posted: 13 Aug 2016 01:29 AM PDT

I have several form fields in my Rails 4 app, which are initially hidden until an earlier question is answered in a particular way.

I have jQuery methods in my javascripts folder to deal with this. It all works fine in development mode. When I try this in production however, it does not work.

Can anyone offer guidance on how to get code that works properly in development to work in production?

Display background job details on a web page without poling

Posted: 13 Aug 2016 02:12 AM PDT

I am updating records from the database using delayed job. i want to display the count of records updated by delayed job on a web page. i can do the ajax polling and can display the count of records updated so far but i think ajax polling is not good way to go since it will add overhead on server.

Is there any alternative of ajax polling.

Rails 4 - dynamically populate 2nd select menu based on choice in first select menu in a nested form

Posted: 13 Aug 2016 01:01 AM PDT

I have models for Project and Ethic in my Rails 4 app.

The ethics view has a nested fields form (using simple form simple fields for) contained in it. The ethic form fields are nested in the projects form.

The ethic form fields has 2 select menus. The first menu offers a set of options for a category. The 2nd select option is a list of subcategories.

I'm trying to figure out how to populate the 2nd select menu with the right options, based on the choice made in the 1st select menu.

In my project.js file, I have:

jQuery(document).ready(function() {       jQuery("#project_ethic_attributes.main_category").change(function() {        var category = $("#project_ethic_attributes.main_category").val(),          sub_category = $("#project_ethic_attributes.sub_category"),          options = [],          str = "";        sub_category.find('option').remove();        if(category == 'Risk of harm'){        options = ["Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]      }       });       // jQuery(".main_category").change(function() {     //  var category = $(".main_category").val(),     //      sub_category = $(".sub_category"),     //      options = [],     //      str = "";     //  sub_category.find('option').remove();       //  if(category == 'Risk of harm'){     //    options = ["Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]     //  }     //  else if(category == 'Informed consent'){     //    options = ["Explanation of research", "Explanation of participant's role in research"]        //  }     //  else if(category == 'Anonymity and Confidentiality'){     //    options = ["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]     //  }     //  else if(category == 'Deceptive practices'){     //    options = ["Feasibility"]     //  }     //  else if(category == 'Right to withdraw'){     //    options = ["Right to withdraw from participation in the project"]       //  }     //  if(options.length > 0){     //    for(i=0;i<options.length;i++){     //      str = '<option value="' + options[i] + '">' + options[i] + '</option>'     //      sub_category.append(str);     //    }     //    sub_category.val(options[0]);     //  }      });  

I can't figure out what Im doing wrong. Regardless of the choice I make in the 1st option, the 2nd select menu is populated with options that belong to the last category.

My projects form has:

 <%= f.simple_fields_for :ethics do |f| %>          <%= render 'ethics/ethic_fields', f: f %>   <% end %>   <%= link_to_add_association 'Add an ethics consideration', f, :ethics, partial: 'ethics/ethic_fields' %>  

My ethic form fields has:

<%= f.input :category, collection: [ "Risk of harm", "Informed consent", "Anonymity and Confidentiality", "Deceptive practices", "Right to withdraw"], :label => "Principle",  prompt: 'select', id: "main_category" %>                  <%= f.input :subcategory,  collection: text_for_subcategory(@category), :label => "Subcategory", prompt: 'select', id: "sub_category" %>  

My ethic view helper has:

def text_for_subcategory(category)        if category == 'Risk of harm'              [ "Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]          elsif category == 'Informed consent'              ["Explanation of research", "Explanation of participant's role in research"]          elsif category == 'Anonymity and Confidentiality'              ["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]          elsif category == 'Deceptive practices'               ["Feasibility"]           else category == 'Right to withdraw'                  ["Right to withdraw from participation in the project"]          end      end    

Can anyone see what i need to do to populate the second select menu with the right options based on the choice made in the 1st select menu. I'm wondering if I'm not supposed to write the jQuery in the project.js file, given the form fields are contained within an ethic view partial (rendered in the projects form).

Basic public API auth without any user or OAuth

Posted: 13 Aug 2016 01:01 AM PDT

My use case is that, I have an mobile app which will allow user to use it without login. But I still kind of want to restrict my API to only my App. I did investigation about different ways but cannot find a very perfect match to my needs. But I think this should be a common case and I must miss some important information somewhere. Note: I'm using rails as backend.

OK, so below is the scheme I investigated and considered.

  1. OAuth2, it seems very common but in my case, I don't have the concept of client in my App. Every app is the same when user is not login.

  2. Try to mimic other platforms, using an api key. But no matter what kind of specific plan I can use, like public/private key, or HMAC signature, or whatever, I was considering that how I should manage the keys on server. E.g. if I use public/private key, then the private key should be stored on my server. And the public key will be stored on mobile device. But what if someday, I want to change the private key? Then if user don't update their app, they will not be able to get the new public key and cannot access to the API. I don't know if I should consider this scenario since I cannot foresee any reason that I want to change my private key. But maybe in some scenario, my server was hacked and my private key leaked out or someone hacked my app and get the private key. So I don't know if my thinking direction is right. Or maybe in these cases, I should think more about how to make sure my server and app are not hacked.

So mostly my question is about the second investigation I made. And also if I miss something, willing to hear. Thanks

How do I select the image column in rails when using where & select clause

Posted: 13 Aug 2016 08:34 AM PDT

I have been using paperclip to upload and fetch image(s) url. My question is how do I select the image column when doing something like this for eg: User table structure id ,name, logo_file_name, logo_content_type + more columns When i do u = User.find(1).logo I get the result which is great. Now when I'm using u = User.select('name', 'logo').where('something') receiving error saying there is no such column as u.logo which is clear to me, since there is no column that's why it's giving me error, but how do fetch image url later condition.

How to parse nested json in rails

Posted: 13 Aug 2016 12:54 AM PDT

I am new to rails. I am trying to consume json in rails. I am not able to consume nested json in rails

Json format is

{  "userId": "String",  "firstName": "String",  "role": [{      "createdTime": 1469361928825,      "updatedTime": 1469361928825,      "createdBy": "String",      "id": "String",      "role": "String",      "explanation": "String",      "locationId": "String",      "hospitalId": "String",      "accessModules": [{          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "READ",              "accessPermissionValue": false          }]      }, {          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "WRITE",              "accessPermissionValue": false          }]      }, {          "module": "CONTACT",          "url": "CONTACT",          "accessPermissions": [{              "accessPermissionType": "HIDE",              "accessPermissionValue": false          }]      }]  }, {      "createdTime": 1469361928831,      "updatedTime": 1469361928831,      "createdBy": "String",      "id": "String",      "role": "String",      "explanation": "String",      "locationId": "String",      "hospitalId": "String",      "accessModules": [{          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "READ",              "accessPermissionValue": false          }]      }, {          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "WRITE",              "accessPermissionValue": false          }]      }, {          "module": "CONTACT",          "url": "CONTACT",          "accessPermissions": [{              "accessPermissionType": "HIDE",              "accessPermissionValue": false          }]      }]  }, {      "createdTime": 1469361928837,      "updatedTime": 1469361928837,      "createdBy": "String",      "id": "String",      "role": "String",      "explanation": "String",      "locationId": "String",      "hospitalId": "String",      "accessModules": [{          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "READ",              "accessPermissionValue": false          }]      }, {          "module": "String",          "url": "String",          "accessPermissions": [{              "accessPermissionType": "WRITE",              "accessPermissionValue": false          }]      }, {          "module": "CONTACT",          "url": "CONTACT",          "accessPermissions": [{              "accessPermissionType": "HIDE",              "accessPermissionValue": false          }]      }]  }],  "isActivate": true,  "lastSession": 1471069942314,  "discarded": false  

}

Rails code is as follows -

response[:data].each do |obj|        users << {          first_name: obj[:firstName],          user_id: obj[:userId],          role_id: obj[:role][:id],          role: obj[:role][:role],          role_type: obj[:role][:accessModules][:accessPermissions][:accessPermissionType],        } unless obj[:discarded]      end      render json: {success: true, users: users}    end  

While consuming JSON I am not able to parse it properly. I

Rails 4 - using a presenter in another controllers view

Posted: 12 Aug 2016 11:31 PM PDT

Is it possible to use a presenter made for my user view with another view.

I have a user presenter with:

def full_name      if first_name.present?          [*first_name.capitalize, last_name.capitalize].join(" ")      else         test full name      end       end  

I also have an assign_roles view (index), which Im trying to use to assign roles to users. In that view, I'm trying to write:

<%= select_tag "users", options_from_collection_for_select(@users, "id", UserPresenter.full_name), { multiple: true , class: "chosen-select form-control" } %>  

How can I access the User model's presenter from another controller's view?

In Rails MVC which one is correct options

Posted: 13 Aug 2016 12:03 AM PDT

Ruby on Rails uses the Model View Controller (MVC) architecture. Which of the following parts functions as the view part of this architecture? PICK ONE OF THE CHOICES

Controllers  Database  Rails Migrations  Asset Tag Helpers  Validation Helpers   

differences between rails5 and previous versions?

Posted: 12 Aug 2016 10:57 PM PDT

What is new in Rails 5. Please explain in detail. I couldn't find a perfect resource to know more about new changes.

Rails 4 - how to write a helper method to present attribute names

Posted: 12 Aug 2016 11:43 PM PDT

I have a roles table with an attribute :name in it.

I'm trying to use a list of role names in a collection select. Instead of listing the :name in the way it is recorded in the database, I want to present it neatly.

For example, :name has an instance stored as :admin in the database. I want to present that in the collection select as 'Administrator'.

I tried to write a roles helper that says:

module RolesHelper

def text_for_role(name)    case name        when 'guest'          'Guest - Trial Account'        when 'admin'          'Administrator'        when 'representative'          'Representative'           etc, etc  

but this option isn't going to work in this context, because I want to list all the roles, but refer to them written nicely.

I have this collection select:

<%= select_tag "roles", options_from_collection_for_select(@roles, "id", "<%= text_for_role(name)%>"), :multiple => true, :class => 'chosen-select form-control' %>  

Can anyone see how I can write a helper or a presenter that can be used on the whole list of collection select options?

Rails 4, Assigning Roles with Rolify

Posted: 12 Aug 2016 10:40 PM PDT

I'm trying to figure out how to assign roles using Rolify.

I have models for User, Role and Organisation. The associations are:

User

rolify strict: true # strict means you get true only on a role that you manually add  attr_accessor :current_role  has_one :organisation, foreign_key: :owner_id   

Role

has_and_belongs_to_many :users, join_table: "users_roles"  belongs_to :resource, :polymorphic => true  

Organisation

resourcify  belongs_to :owner, class_name: 'User'  

I made a new controller called assign_roles_controller.rb. It has:

class AssignRolesController < ApplicationController      def index      @roles = Role.all #rewrite to exclude the global roles which are for admin only      @users = User.all      # @users = Organisation.find(@current_user.organisation).user.profiles        @organisation = Organisation.first      # @organisation = Organisation.find(@current_user.organisation)    end        def create      @user = User.find(params[:id])      @role = Role(role_params)      @organisation = Organisation.first      @user.add_role, @role, @current_user.organisation    end  

My objective is for the user that is the owner of an organisation - any roles that user assigns to other users, will be scoped to the first user's organisation.

I'm not trying to figure out how to find the relevant users or organisations yet- I've hard wired them to pick all users and the first organisation just to see if I can make the create action work.

I have made an index view for assign_roles/index:

<div class="row">    <div class="col-md-3 col-md-offset-2">      <%= select_tag "users", options_from_collection_for_select(@users, "id", "formal_name"), { multiple: true , class: "chosen-select form-control" } %>      </div>    <!-- # roles -->    <!-- u.add_role role, current_user.org -->    <div class="col-md-3 col-md-offset-1">      <%= select_tag "roles", options_from_collection_for_select(@roles, "id", "<%= text_for_role(name)%>"), :multiple => true, :class => 'chosen-select form-control' %>      </div>  </div>  

Can anyone see where I'm going wrong. The create action doesnt work at all.

How to generate private key file of Amazon EC 2 Server in Ruby on Rails 4?

Posted: 13 Aug 2016 12:31 AM PDT

I want to generate private key file for amazon server in Rails 4. I have an instance running in Amazon for Ruby on Rails. But I don't have its private key file. So will you please let me know from where I may regenerate my private key file so that I can push my code to amazon server via git.

how to configure the sqlite3 database in rails version 2.3.14?

Posted: 12 Aug 2016 11:19 PM PDT

I know the rails version 2.3.14 is outdated. But I need to learn how older versions work.

I created a new rails application, in that application I created a controller called pages and for that controller I created the home and contact actions.

I added the below line in the routes.rb file,

map.root :controller => 'pages', :action => 'home'  

And I also removed the index.html file in the public directory.

If I run the server and connect to that server in the browser using

localhost:3000  

It does not load the home page. In server it gives the following error.

  Status: 500 Internal Server Error    no such file to load -- sqlite3  

But in the same system in another rails application it works fine. That application is copied from other system. It does not gives that error.

Can anyone please explain me how to fix this problem?

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete