Sunday, June 19, 2016

How to sort an array of Integer and OpenStruct objects by a key of one of the OpenStruct Keys | Fixed issues

How to sort an array of Integer and OpenStruct objects by a key of one of the OpenStruct Keys | Fixed issues


How to sort an array of Integer and OpenStruct objects by a key of one of the OpenStruct Keys

Posted: 19 Jun 2016 08:11 AM PDT

I am just learning Ruby and started working with arrays. I have an array that looks like:

easyStats = [<SampleArray: @id=0, @stats=#<OpenStruct total_sessions_played=244, total_sessions_lost=124>>,                <SampleArray: @id=1, @stats=#<OpenStruct total_sessions_played=204, total_sessions_lost=129>>,                <SampleArray: @id=2, @stats=#<OpenStruct total_sessions_played=2, total_sessions_lost=4>>]  

I can sort the array by the id (Integer) attribute as such:

easyStats.sort_by(&:id)  

However, what I would like to do is sort the array by a key of the OpenStruct object, I have tried the following options with different errors:

easyStats.sort_by(&:stats)  

Error: comparison of OpenStruct with OpenStruct failed

easyStats.sort_by(&:stats[:total_sessions_played])  

Error: no implicit conversion of Symbol into Integer

easyStats[:stats].sort_by(&:total_sessions_played)  

Error: no implicit conversion of Symbol into Integer

I have seen solutions on how to sort an array of just one OpenStruct object and I think I understand it - How to sort a ruby array by two conditions

Could someone show me how to sort by any key of the OpenStruct object in this example (Array with Integer and OpenStruct objects)?

I'm trying to parse some table and they have some weird alphabet-like non-ascii character

Posted: 19 Jun 2016 07:56 AM PDT

RIZALTE

I have some weird characters like the ones above. On google, it works and it even searches the same characters on the web browser search function, but it does not match on the ruby console.

What is this..? Is there some kind of table that can replace this to normal alphabets?

Error PArsing Gemfile "syntax error , unexpected tSTRING

Posted: 19 Jun 2016 07:18 AM PDT

I am a total newbie. I'm doing the Rubytutorial by Michael Hartl and yesterday everything worked and I was able to publish Hello World-using cloud9 IDE as recommended by the book.

This morning however, it seems that the Turbolinks Gem in the gemfile has a syntax error. And as a result, it is not letting me publish the page.

Here is the error, as listed :

[!] There was an error parsing Gemfile: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '(' - gem 'turbolinks', '2.3.0' ^ /home/ubuntu/workspace/hello_app/Gemfile:20: syntax error, unexpected ',', expecting end-of-input gem 'turbolinks', '2.3.0'

Here is a picture of the Gemfile:

enter image description here

I can't seem to recognize what the syntax error is.

Here is the image of the syntax error:

enter image description here

How to present a list in views for this

Posted: 19 Jun 2016 07:23 AM PDT

I want to present products based on a user attribute. So basically I'm retrieving an object from product class based on user attribute. I don't know how to create a list in my views for those. How can I present them by an attribute? These are my views below right now where I'm showing all products:

<% @products.each do |product| %>        <%= render "product_row", product: product, order_item: @order_item %>      <% end %>  

My user.rb

def products_for_gender      if gender == 'male'        Product.where("product_id: '9'")      elsif gender == 'female'        Product.where("product_id: '10'")      else        Product.where("product_id: '11'")      end    end  

And my controller:

def index      @products = Product.all      @products = current_user.products_for_gender      @order_item = current_order.order_items.new    end  

Right now I'm getting this error when I try to access product views:

ActiveRecord::StatementInvalid in Products#index  Showing /home/ubuntu/workspace/app/views/products/index.html.erb where line #31 raised:    SQLite3::SQLException: unrecognized token: ":": SELECT "products".* FROM "products" WHERE "products"."active" = ? AND (product_id: '9')  

Rails route file behaving differently in Heroku vs Localhost

Posted: 19 Jun 2016 06:28 AM PDT

The responsible code is not environment specific yet it works locally but not in production:

POST request to my app's /oauth/token should redirect to a controller overriding default Doorkeeper Token response as shown in the first route

routes.rb

require 'api_constraints'    Rails.application.routes.draw do    use_doorkeeper do      controllers :tokens => 'access_token'    end    # Other routes  end  

The above works fine on a local server however in production[Heroku] this seems to be ignored and is instead routed to default doorkeeper class for no apparent reason. Therefore the response with the token does not contain the user id.

REQUEST TO "https://myapp.herokuapp.com/oauth/token"

POST /oauth/token HTTP/1.1  Host: myapp.herokuapp.com  Cache-Control: no-cache  Postman-Token: xxxxxxxx  Content-Type: application/x-www-form-urlencoded    grant_type=password&email=john%40gmail.com&password=password  

THIS RETURNS JSON RESPONSE:

{  "access_token": "XXXXXX",  "token_type": "bearer",  "created_at": 1466340696  }  

The same request to "http://localhost:3000/oauth/token" returns

{  "access_token": "XXXXXX",  "token_type": "bearer",  "created_at": 1466341435,  "id": 1  }  

with the correctly included user_id. I'm not sure if there is some kind of a cache issue which makes my production server use the old routes file. I've tried restarting dynos and push further changes to to heroku master however this did not resolve the issue.

access_token_controller

class AccessTokenController < Doorkeeper::TokensController      # Overriding create action    # POST /oauth/token    def create      response = strategy.authorize      body = response.body        if response.status == :ok        # User the resource_owner_id from token to identify the user        user = User.where(response.token.resource_owner_id).first rescue nil          unless user.nil?          ### If you want to render user with template          ### create an ActionController to render out the user          # ac = ActionController::Base.new()          # user_json = ac.render_to_string( template: 'api/users/me', locals: { user: user})          # body[:user] = Oj.load(user_json)            ### Or if you want to just append user using 'as_json'          body[:id] = response.token.resource_owner_id        end      end        self.headers.merge! response.headers      self.response_body = body.to_json      self.status        = response.status      rescue Doorkeeper::Errors::DoorkeeperError => e      handle_token_exception e    end  end  

Apologies for any confusion and thank you in advance for any assistance with this.

How to implement autocomplete with typeahead and searchkick?

Posted: 19 Jun 2016 06:17 AM PDT

So I've got Page controller:

class PagesController < SiteController    .    .    def autocomplete      render json: Model.search(params[:q], autocomplete: true, limit: 10).map(&:name)    end    .    .  end  

and Model model:

class Model < ActiveRecord::Base    searchkick autocomplete: ['name']    .     .  end  

On my home page(app/views/pages/index.html.erb) I've got search form:

<form id="home-search" method="get" action="full_search" class="full-search" data-remote="true">    <%= text_field_tag :q, params[:q], id: "query_field", autocomplete: "off" %>    <input type="submit" value="ИСКАТЬ">  </form>  

In app/views/layouts/application.html.erb I added this in head tag:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/typeahead.min.js"></script>  

I added route to routes.rb

get '/autocomplete' => 'pages#autocomplete'  

And finnaly I created file app/assets/javascripts/pages.js.coffee with this:

$ ->    $('#q').typeahead      name: "model"      remote: "/autocomplete?q=%QUERY"  

I followed this tutorial http://blog.ragnarson.com/2013/10/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch.html

When I downloaded the project from that tutorial and typed something I got autocomplete and in my console was this:

Processing by BooksController#autocomplete as JSON    Parameters: {"query"=>"j"}    Book Search (144.5ms)  curl http://localhost:9200/books_development/_search?pretty -d '{"query":{"multi_match":{"fields":["title.autocomplete"],"query":"j","analyzer":"searchkick_autocomplete_search"}},"size":10,"from":0,"fields":[]}'    Book Load (12.5ms)  SELECT "books".* FROM "books" WHERE "books"."id" IN (1)  

In my project nothing is going on when I type something. Only if I go to http://localhost:3000/autocomplete?q=a I got ["A3","A6","AX","A5","A2","A4","A8","Aska","Arna","Altea"] on page (that's exactly what I need. But I need this to be as autocomplete). And in my console:

Processing by PagesController#autocomplete as HTML    Parameters: {"q"=>"a"}    Model Search (120.2ms)  curl http://localhost:9200/models_development/_search?pretty -d '{"query":{"multi_match":{"fields":["name.autocomplete"],"query":"a","analyzer":"searchkick_autocomplete_search"}},"size":10,"from":0,"fields":[]}'    Model Load (0.2ms)  SELECT `models`.* FROM `models`  WHERE `models`.`id` IN (26, 29, 847, 28, 81, 27, 30, 982, 1041, 380)  

So what am I doing doing wrong?Looks like typeahead doesn't work...

Ruby on Rails error during installation

Posted: 19 Jun 2016 05:52 AM PDT

I'm trying to install Ruby, I followed the installation guide well, but when I tried to run the server by the command: ruby bin/rails setup after I created the controller called blog as described in the instructions, it gave me an error in red and a text in yellow: Error: Could not find gem uglifier <>= 1.3.0 in the gems available on the machine.

Yes! I know that this is a Googleable question but all I can get are solutions for people with internet access on their PC.

But unfortunately, my computer doesn't have a working Internet connection. I'm posting this question from my phone. So I'm unable to install uglifier(if that's the required thing to do) through the command prompt. Many thanks.

Random record selction and pagiantion in rails 4

Posted: 19 Jun 2016 07:40 AM PDT

I need to select random 5 records in sqlite3 and paginate them.

def test      add_breadcrumb "Age Test", ages_test_url      @posts = Age.limit(5).order('RANDOM()')      @posts = @posts.page(params[:page]).per_page(2)  end  

The above code displays all the record but I need only 5.

Not found .map extension from node_modules in rails app

Posted: 19 Jun 2016 05:38 AM PDT

I try to integrate angular to rails app. I extended assets folder by

config.assets.paths << Rails.root.join('node_modules')  

and it's good work but my console has serveral messages error

http://localhost:3000/assets/rxjs/Subject.js.map

Rails app couldn't .map extension how to load it

How to call api in bundle new gem using httpclient

Posted: 19 Jun 2016 05:03 AM PDT

I make a new gem in rails using bundle gem . Now I want to call some API in it. But I can't see any tutorial related to that. If anyone know please give link or anything.

Heroku Error: Command 'exec' not recognized

Posted: 19 Jun 2016 04:59 AM PDT

I am not sure if something has changed recently on Heroku but when I run heroku run rake db:migrate

I get the following error:

Running rake db:migrate on ⬢ protected-bastion-81018... up, run.9931  Error: Command 'exec' not recognized  Usage: rails COMMAND [ARGS]    The most common rails commands are:   generate    Generate new code (short-cut alias: "g")   console     Start the Rails console (short-cut alias: "c")   server      Start the Rails server (short-cut alias: "s")   dbconsole   Start a console for the database specified in config/database.yml               (short-cut alias: "db")   new         Create a new Rails application. "rails new my_app" creates a               new application called MyApp in "./my_app"    In addition to those, there are:   destroy      Undo code generated with "generate" (short-cut alias: "d")   plugin new   Generates skeleton for developing a Rails plugin   runner       Run a piece of code in the application environment (short-cut alias: "r")    All commands can be run with -h (or --help) for more information.  

rake db:migrate works fine locally and my app is OK on my local machine. Any ideas how to fix this?

rails bootstrap modal partial

Posted: 19 Jun 2016 04:52 AM PDT

Using Rails 4.2.6, Bootstrap-saas 3.2.0 I have a collection of products which i'm rendering in my index view like this. Using bootstrap gridsystem

.row    =render partial: 'product', collection: @products  

The product partial

   .col-sm-6.col-md-4      .thumbnail      %h2 My Box      %ul        %li=product.name        %li=product.brand        %li=product.model        %li="$#{product_price(product.price)}"        =link_to 'more info', '#dialog', 'data-toggle' => 'modal'  

I want to display a modal for each rendered product with product.description,product.name displayed in the modal. The problem I'm having is, the modal is only loading with the first product information only. It's supposed to show product information for each product. my modal html markup

    #dialog.modal.fade{'aria-hidden' => 'true', 'aria-labelledby' =>         'myModalLabel', 'data-backdrop' => 'static', 'data-keyboard' => 'true', :role => 'dialog', :tabindex => '-1'}    .modal-dialog      .modal-content        .modal-header          %button.close{'aria-label' => 'Close', 'data-dismiss' => 'modal', :type => 'button'}            %span{'aria-hidden' => 'true'} &times;          %h3.modal-title=product.name        .modal-body          %h2=product.desc        .modal-footer          =button_tag 'close', 'data-dismiss' => 'modal'  

rails - Getting an id from the url and then passing it as an argument for creating an object

Posted: 19 Jun 2016 05:05 AM PDT

First off I would like to ask how to redirect after clicking the submit button in a creation form. I have a form for creating a quiz and after they hit submit I want to redirect them to the link 'quiz/:id/add_question' where :id is the id of the just created quiz, but instead I just get redirected to /quizzes and it leads to a "The connection was reset" error in my browser.

Here is my quiz form:

<div>  <h2>Create Quiz</h2>  <%= form_for(@quiz) do |f| %>      <div>          <%= f.label :name %>          <%= f.text_field :name %> </br>            <%= f.label :subject %>          <%= f.text_field :subject %>      </div>      <%= f.submit "Submit" %>  <% end %>  </div>  

And my quizzes controller:

class QuizzesController < ApplicationController      def new           @quiz = Quiz.new      end        def create          @quiz = Quiz.new(quiz_params)          flash[:success] = "Quiz Created successfully" if @quiz.save          redirect_to 'quiz/' + @quiz.id.to_s + '/add_question'      end         private        def quiz_params          params.require(:quiz).permit(:name, :subject)      end  end  

The quiz/:id/add_question link leads to a question creation form:

<div>  <%= form_for(@question) do |f| %>      <%= f.label :question %></br>      <%= f.text_field :question %></br>        <%= f.label :answer1 %></br>      <%= f.text_field :answer1 %></br>        <%= f.label :answer2 %></br>      <%= f.text_field :answer2 %></br>        <%= f.label :answer3 %></br>      <%= f.text_field :answer3 %></br>        <%= f.label :answer4 %></br>      <%= f.text_field :answer4 %></br>        <%= f.label :correct_id %></br>      <%= f.text_field :correct_id %></br>        <%= f.submit "Add question" %>      <% end %>  </div>  

The other part of my question is how can I pass another argument for the creation of the question object here. I don't want the user to enter that argument because the argument should be the id from the current url (quiz/:id/add_question).

Trigger puffing billy only on specific tests by using rspec metadata

Posted: 19 Jun 2016 07:20 AM PDT

I would like to switch to webkit_billy (the js driver of puffing billy gem) only in certain tests. I want to be able to use :

describe "xxx", billy: true do  end  

This would signal to rspec that I want to switch to puffing biller driver.

I wrote this in spec_helper.rb but it's not working:

  config.before(:each) do |example|      if [:billy].include? example.metadata[:type]        Capybara.current_driver     = :webkit_billy        Capybara.javascript_driver  = :webkit_billy      else        Capybara.current_driver     = :webkit        Capybara.javascript_driver  = :webkit       end    end  

Note: I would

Rails 4 - change data type of a column from binary to string

Posted: 19 Jun 2016 07:34 AM PDT

In my model "projectttype" I have a column "image" created with t.binary :image and I need to change it to data type string.

This would be my first migration and am unsure how to name the migration.

"ChangeImageOnProjecttypes" - does it matter?

And add to the migration file: change_column :projecttype, :image, :string

Is this correct or if not, what should it be?

Thanks.

omniauth callback routes mapping issue

Posted: 19 Jun 2016 03:03 AM PDT

Since I am new to Rails, I am not able to figure out the proper way for mapping the urls.

I have just integrated the ominauth plugin in existing app. I need to map the callback url (auth/:provider/callback) to my session controller's create method, I have added a route like this:

get 'auth/:provider/callback', to: 'overrides/sessions#create'  

Also, the routes for my login system:

mount_devise_token_auth_for 'User', at: 'auth', controllers: {          registrations: 'overrides/registrations',          sessions: 'overrides/sessions',          token_validations: 'overrides/token_validations'      }  

Here is my session controller:

module Overrides    class SessionsController < DeviseTokenAuth::ApplicationController      before_filter :set_user_by_token, :only => [:destroy]        def create        # ...  

it is working for simple login but it throws an exception on callback url with message

Could not find devise mapping for path "/auth/google_oauth2/callback?  

One thing I have notice is that if I change this:

class SessionsController < DeviseTokenAuth::ApplicationController  

To this:

class SessionsController < ApplicationController  

Then url is found but everything breaks for obvious reason.

Can anyone please suggest the correct mapping?

Angular / Rails net::ERR_TOO_MANY_REDIRECTS on update

Posted: 19 Jun 2016 04:09 AM PDT

In my Rails app I have included a small angular app, which uses a plug-in to upload a file to Amazon S3. The code is embedded in a rails page.

After the file is successfully uploaded to S3, I wish to save the S3 key (a string) in the Rails backend using the Rails update action. I then wish to redirect to the show action on the same rails controller. The job of Angular is finished then, and there is no Angular on the show page.

So far it is all working, including the successful save of the update, and there is no error from Rails, but Angular emits the dreaded "net::ERR_TOO_MANY_REDIRECTS" error.

Note that I am not using any Angular routing, and in fact would like to avoid doing so and have Rails control page refreshes.

Rails controller code:

  def update      respond_to do |format|       if @user.update(secure_params)         format.html { redirect_to @user }         format.json { head :no_content }         format.js       else         format.json { render json: @user.errors.full_messages,                                    status: :unprocessable_entity }       end     end   end  

Angular update

 $scope.upload = function (dataUrl, file) {      $scope.aws_file_key = $scope.aws.key + file.name;      Upload.upload({          url: $scope.aws.url,          method: 'POST',          data: {              key: $scope.aws_file_key,              AWSAccessKeyId: $scope.aws.access_key,              acl: $scope.aws.acl,              policy: $scope.aws.policy,              signature: $scope.aws.signature,              "Content-Type": file.type != '' ? file.type : 'application/octet-stream',              file: file          },      }).then(function (response) {          console.log('updateUser');          $timeout(function () {            updateUser();          });      }, function (response) {          console.log('response');          if (response.status > 0) $scope.errorMsg = response.status              + ': ' + response.data;      }, function (evt) {          console.log('evt');          $scope.progress = parseInt(100.0 * evt.loaded / evt.total);      });  }    function updateUser() {    $http({       method: 'PATCH',       url: '/users/' + $scope.user.id,       dataType: 'json',       contentType: 'application/json',       data: {user: { profile_image_s3_key: $scope.aws_file_key }}    });  // $http  }  // updateUser()  

enter image description here

How do I combine these two snippets of CoffeeScript into 1 file that works?

Posted: 19 Jun 2016 03:00 AM PDT

So I have two snippets that work independently:

$ ->      $('[data-provider="summernote"]').each ->        $(this).summernote          height: 300  

And this:

$ ->    companySelect = $('#company-select')    jobFields = $('#job-fields')    companySelect.change ->      # if selected option is the first option      if $(this).find('option:selected').index() == 1        jobFields.show().find(':input').prop 'disabled', false      else        jobFields.hide().find(':input').prop 'disabled', true      return    # call change immediately so this still works when already updating and not just creating.    companySelect.change()    return  

Given that these two snippets govern two things within the Jobs#Views, I would like to combine them both in my jobs.coffee file.

But I am not quite sure how to put both of them in the same file so they both work without interfering with each other.

I tried some stuff, but since I don't really fully understand CoffeeScript I am sure I did it wrong, so that didn't work.

How do I make this snippet of CoffeeScript TurboLinks 5 friendly?

Posted: 19 Jun 2016 03:00 AM PDT

I have the following:

$ ->      $('[data-provider="summernote"]').each ->        $(this).summernote          height: 300  

And this works, however, I would like to make it TurboLinks 5 friendly.

So I tried the following:

$ ->    ready = ->      $('data-provider="summernote"]').each ->        $(this).summernote          height: 300      $(document).ready(ready)    $(document).on('page:load', ready)  

But I keep getting this error:

Uncaught ReferenceError: ready is not defined  

How do I fix this so that I make the original snippet TL-5 friendly?

Edit 1

By the way, I am doing this in my jobs.coffee file, which I know is being included in my asset-pipeline. So that's not it.

How can I add custom name and Id to a time_select

Posted: 19 Jun 2016 04:17 AM PDT

I've a time_select and I want to add a custom name and id to the inputs, i tried with:

<td>     <%= f_messenger.time_select :schedules,         :id => "messenger_schedules_#{day}_end",         :name => "messenger[schedules][#{day}][end]"     %>  </td>  

if I tried this with text inputs it works but on time_select I get something like:

<select id="messenger_schedules_4i" name="messenger[schedules(4i)]">

any ideas?

How should I submit my quiz form?

Posted: 19 Jun 2016 01:28 AM PDT

I guess my problem is two-fold:

  1. Is there a tried-and-true way for creating a form that displays questions and answers? Right now I'm just displaying the question and answer, but giving the user no option to select his or her choice (the correct answer part were just to test that I can correctly set which answers are correct). I have nested models of Survey > Question > Answer

surveys/show.html.erb:

<ol>    <% @survey.questions.each do |question| %>    <li class = 'question'><%= question.content  %>    <ul>      <% for answer in question.answers %>        <li class = 'answer'>      <%= answer.content %>      <%if answer.correct_answer == true %>      <span> <b>Correct Answer</b> </span>      <% else %>      <span> <b>Incorrect Answer</b></span>      <% end%>      </li>        <% end %>    </ul>    </li>      <% end %>  </ol>  
  1. I can't decide on where whatever form I end up with should POST to. I would typically just submit to the create action in the same controller, but right now I'm using that action to create the survey. Should I add another controller SurveyAnswer, and then have it post to that controllers create action? Then have that controller's show action show the quiz results?

Send 'behalf of' mailgun in Outlook Gmail

Posted: 19 Jun 2016 01:27 AM PDT

I try to send email via Mailgun service. I have domain mg.domain.com that verified in the DNS (TXT records). I try to send email from user@some_domain.com and the credentials is the mailgun service mg.domain.com.

I defined the 'From' in the code as user@some_domain.com

In Gmail i get the email like this:

user@some_domain.com via mg.domain.com  

But in Outlook i get:

user=some_domain.com@mg.domain.com on behalf of user@some_domain.com  

Why?

I want to get in outlook the same as in Gmail, with the '='.

Actually, i want to send from info@mg.domain.com, i mean:

user@some_domain.com on behalf of info@mg.domain.com  

Is it possible?

Thanks!

Getting "Filter chain halted as :validate_account_update_params rendered or redirected" when trying to update user

Posted: 19 Jun 2016 01:04 AM PDT

I am using ng-token-auth and devise_token_auth for authentication. When I am trying to update user using

$auth.updateAccount  

it's showing me

Unpermitted parameters: credentials, registration  Filter chain halted as :validate_account_update_params rendered or redirected  

I have included the following in application_controller.rb

before_action :configure_permitted_parameters, if: :devise_controller?  private  def configure_permitted_parameters   devise_parameter_sanitizer.for(:sign_up) << :name   devise_parameter_sanitizer.for(:account_update) << :name << :credentials  end  

Also, credentials field is serialized as an Array in the User model

class User < ActiveRecord::Base   serialize :credentials, Array  end  

How to get the collection of objects of the `has_many` polymorphic association?

Posted: 19 Jun 2016 01:37 AM PDT

I would like to create a gem (github) that includes ActiveRecord model Site that can be associated with AdminUser model in the existing Rails application.

model Site:

module C80SassSeo    class Site < ActiveRecord::Base      belongs_to :owner, :polymorphic => true    end  end  

model Owner:

module C80SassSeo      module Owner        extend ActiveSupport::Concern        #  ERROR THROWN: Cannot define multiple 'included' blocks for a Concern      # included do      #      # end        def self.included(klass)        klass.extend ClassMethods        # klass.send(:include, InstanceMethods)      end        module ClassMethods        def act_as_owner          class_eval do            has_many :sites, :as => :owner, :class_name => 'C80SassSeo::Site'          end        end      end      end  end    ActiveRecord::Base.send :include, C80SassSeo::Owner  

migration for Site (c80_sass_seo_ - table prefix):

class CreateC80SassSeoSites < ActiveRecord::Migration    def change      create_table :c80_sass_seo_sites, :options => 'COLLATE=utf8_unicode_ci' do |t|        t.string :url        t.string :owner_type # NOTE:: without this activeadmin throws an error on index Sites page        t.references :owner, index: true        t.timestamps      end      # add_foreign_key :c80_sass_seo_sites, :owners # NOTE:: migration error occurs, comment it    end  end  

activeadmin for Site:

 ActiveAdmin.register C80SassSeo::Site, as: 'Site' do       scope_to :current_admin_user, association_method: :sites_list       menu :label => "Sites"       permit_params :url, :owner_id       config.sort_order = 'id_asc'       index do       column :url       actions     end       form(:html => {:multipart => true}) do |f|         f.inputs 'Properties' do         f.input :owner_id, :input_html => { :value => current_admin_user.id }, as: :hidden         f.input :url       end         f.actions     end     end  

BUT I'm getting an empty collection any time I try to access admin_user.sites for a AdminUser instance:

=> #<ActiveRecord::Associations::CollectionProxy []>  

Is the correct way to fetch admin users' sites by implementing method like 'sites_list'?

model AdminUser (host application):

require 'c80_sass_seo/owner'    class AdminUser < ActiveRecord::Base    devise :database_authenticatable,            :recoverable, :rememberable, :trackable, :validatable      act_as_owner      def sites_list      C80SassSeo::Site.where(:owner_id => self.id)    end    end  

Rails code protection

Posted: 19 Jun 2016 01:37 AM PDT

I want to ask about techniques used for code protection for Rails app. I do know about Rubyencoder, but I wanted to know if there is any other alternative solution?

redirect_to next instance on update

Posted: 19 Jun 2016 12:00 AM PDT

I'm trying to redirect users to the next instance of my WordExposition model after update. What I have currently works for immediately-adjacent word_exposition id's, but raises RecordNotFound if the next lesson's word_exposition's ID skips (i.e. it will redirect properly between id's 1-4, but will break if the next id is 6). How can I get it to redirect also for those non-adjacent WordExposition instances that belong to the same lesson?

I based the next_exposition model method on the ideas from this post, but I'm missing something to get it to work here.

WordExposition model:

class WordExposition < ActiveRecord::Base    belongs_to :enrollment    belongs_to :word      def next_exposition      WordExposition.where(["id > ? AND enrollment_id = ?", id, enrollment_id]).first    end  end  

WordExpositions controller:

class WordExpositionsController < ApplicationController    def update      current_word_exposition      @current_word_exposition.completed = true      @current_word_exposition.term_given_by_student = params[:word_exposition][:term_given_by_student]      if @current_word_exposition.save        flash[:notice] = "Congratulations!"        #currently only redirects correctly for adjacent words in the same lesson, should do so for non-adjacent word_expositions in the same lesson        if next_word = @current_word_exposition.next_exposition          redirect_to lesson_word_exposition_path(current_lesson, next_word)        end       else        flash[:alert] = "Enter the word exactly as shown!"        redirect_to lesson_word_exposition_path(current_lesson, current_word_exposition)      end    end      private      helper_method :current_lesson    def current_lesson      @current_lesson ||= Lesson.find(params[:lesson_id])    end      helper_method :current_enrollment    def current_enrollment      @current_enrollment ||= Enrollment.find_by!(lesson_id: params[:lesson_id], user_id: current_user.id)    end      def word_exposition_params      params.require(:word_exposition).permit(:completed)    end      helper_method :current_word_exposition    def current_word_exposition      @current_word_exposition ||= current_enrollment.word_expositions.find_by!(word_id: params[:id])    end  end  

Application failure when deploying heroku app

Posted: 19 Jun 2016 12:22 AM PDT

I run heroku open I get an application error. I check the logs and this is there:

2016-06-19T05:22:44.640391+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=drawparty-.herokuapp.com request_id=6712804b-95f9-49ce-92a5-7f45df7bb79e fwd="108.172.11.245" dyno= connect= service= status=503

I cannot seem to fix this error. Some things I have tried:

heroku restart  bundle install  heroku run rake db:migrate  

The error is H10 which is found here (where's the solution?): https://devcenter.heroku.com/articles/error-codes#h10-app-crashed

Refactoring Controller, where to create new methods?

Posted: 18 Jun 2016 10:26 PM PDT

I have been working on refactoring out my controller and the question I have keep running into is where should I be creating controller specific methods?

For instance, my create action within a controller would currently look like:

scores_controller.rb    def create      @score = @user.scores.new(score_params)      if @score.save        set_shuffled_questions(@score, params[:score][:selected])        questions = Score.build_quiz(@score, params[:score][:selected])        question = questions.shuffle.first        cookies[:question] = question.question        flash[:success] = "Begin quiz, good luck!"        redirect_to score_quiz_path(@score, question)      else        flash[:alert] = "You suck"        render 'new'      end    end  

I am starting to work towards using Sandi Metz' rules for developers, one of them being: Five lines per method. My most natural instinct other than creating an entirely new class filled with methods for this controller would be to put it within the model Score.rb. If that was the case I would be able to change the method to:

score.rb    # Creates quiz with shuffled questions.    def set_shuffled_questions(selected)      questions = Score.build_quiz(self, selected)      question = questions.shuffle.first      cookies[:question] = question.question      flash[:success] = "Begin quiz, good luck!"      redirect_to score_quiz_path(self, question)    end    scores_controller.rb        def create      @score = @user.scores.new(score_params)      if @score.save        @score.set_shuffled_questions(params[:score][:selected])      else        flash[:alert] = "You suck"        render 'new'      end    end  

I am fairly certain this is not the correct way to do it, being that you can not set persistent cookies from the model. What is the appropriate way to refactor controllers with methods?

Making a survey app, how should I delete questions (and add some layout)?

Posted: 18 Jun 2016 10:24 PM PDT

I'm making a survey app using a Survey model, which has_many Questions which itself has_many answers. The form partial looks like this:

<%= form_for(@survey) do |f| %>    <% if @survey.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>          <ul>        <% @survey.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>        <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>      <%= f.fields_for :questions do |question_attribute| %>    <p>      <%= question_attribute.label :content, "Question" %><br />      <%= question_attribute.text_area :content, :rows => 3 %>    </p>       <%= question_attribute.fields_for :answers do |answer_attribute| %>      <p>        <%= answer_attribute.label :content, "Answer" %>        <%= answer_attribute.text_field :content %>        </p>     <% end %>    <% end %>           <div class="actions">      <%= f.submit %>    </div>  <% end %>  

and is called by the edit and new actions. quick side note: how is it that rails fills in previous question/answer values in the form when called by the edit action?

I want to make it so that when I visit each survey's edit page, beside each question will be a "delete" link, and when I press that delete link the question is deleted from the survey and I'm directed back to the edit page. How should I accomplish this? I took a look at some railscasts but everything they did had been deprecated already.

In addition, right now when I show a survey, the questions aren't numbered ie Question 2, Question 2, etc. and the Answers for each question aren't numbered a), b), c), d), e). How do I make rails automatically number these when I create a survey? My show form looks like this:

<p id="notice"><%= notice %></p>    <p>    <strong>Name:</strong>    <%= @survey.name %>  </p>    <ol>    <% @survey.questions.each do |question| %>    <li><%= question.content  %>    <ul>      <% for answer in question.answers %>        <li><%= answer.content %></li>        <% end %>    </ul>    </li>      <% end %>  </ol>      <%= link_to 'Edit', edit_survey_path(@survey) %> |  <%= link_to 'Back', surveys_path %>  

Bundler is removing RUBY VERSION from Gemfile.lock

Posted: 18 Jun 2016 09:04 PM PDT

I'm having the opposite issue to this one. The Gemfile has:

source 'https://rubygems.org'  ruby '2.3.1'  

At the end of my Gemfile.lock file is:

RUBY VERSION     ruby 2.3.1p112     BUNDLED WITH      1.12.4  

But when I run bundle install is always deleting RUBY VERSION regardless I'm using the same as the development team's version. Even I'm using a more recent bundler version than the used to generate the original Gemfile.lock file:

$ bundle -v  Bundler version 1.12.5  $ ruby -v  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]  

Any ideas how can I stop this?

No comments:

Post a Comment