Wednesday, September 21, 2016

Uploading files by ng-file-upload and paperclip | Fixed issues

Uploading files by ng-file-upload and paperclip | Fixed issues


Uploading files by ng-file-upload and paperclip

Posted: 21 Sep 2016 08:10 AM PDT

I spent a lot of times with ng-file-upload and rails paperclip and stuck((. In standard view with new.html.erb paperclip works perfect. But with ng-file-upload browser returns an error.

Internal Server Error    bad content body  

Or if I change upload in my controller:

afisha: {file: file} => to file: {file: file}  

Routing Error:

Routing Error  No route matches [POST] "/public"  

Here is my controller:

$scope.upload = function (file) {             console.log(file);              Upload.upload({                  url: 'http://localhost:3000/public',                  method: 'POST',                  afisha: {file: file}              }).then(function (resp) {                  console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);              }, function (resp) {                  console.log('Error status: ' + resp.status);              }, function (evt) {                  var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);                  console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);              });          };  

View:

<button class="btn" ngf-select="upload($file)">Upload on file select</button>  

Rails controller:

class EventsController < ApplicationController      respond_to :json    before_filter :authenticate_user!        def index      respond_with Event.all    end    def show      respond_with Event.find(params[:id])    end    def create      @event = Event.create(event_params)      @guests = guests_params[:guests].map { |guest|        Guest.create(name: guest[:name], surname: guest[:surname], event: @event)      }      respond_with @event    end      def destroy      @event = Event.find(params[:id])      @event.destroy      end      def authenticate_user!      if user_signed_in?        super      else        redirect_to login_path      end    end      private    def event_params      params.require(:event).permit(:name, :description, :date, :afisha)    end    def guests_params      params.permit(guests: [:name, :surname])    end  end  

model:

class Event < ActiveRecord::Base      has_attached_file :afisha, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :afisha, content_type: /\Aimage\/.*\z/      has_many :guests      def as_json(options={})      super(options.merge(include: :guests))          .merge(:afisha => afisha.url)    end    end  

Attaching AXLSX view to mail Rails Mailer

Posted: 21 Sep 2016 08:07 AM PDT

According to the GitHub Page for the axlsx gem I should use this syntax to render a xlsx view to a file and attach it:

xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "users/export", locals: {users: users}  attachments["Users.xlsx"] = {mime_type: Mime::XLSX, content: xlsx}  

Here is my mail method:

xlsx = render_to_string(handlers: [:axlsx], formats: [:xlsx], template: 'v1/reports/reportxyz', params: {start_date: '2016-09-12', period: 'weekly'})  attachments["report.xlsx"] = {content: xlsx, mime_type: Mime::XLSX}  mail(to: "my@email.address", subject: "Report", format: "text")  

However I get this error when I try and call the mailer method:

ActionView::MissingTemplate: Missing template layouts/mailer with {:locale=>[:en], :formats=>[:xlsx], :variants=>[], :handlers=>[:axlsx]}. Searched in:    * "path/to/project/app/views"  

Why is the render_to_string method affecting what the mailer view the mailer is trying to render? locgially I don't have a mailer.xlsx.axlsx file in my app/views/layouts folder but rather the mailer.text.erb I am trying to use as with other emails.

Rails - in `private': nil is not a symbo l (TypeError)

Posted: 21 Sep 2016 08:23 AM PDT

it appears in the production server, while in local server it not appears, the issue is in the Subscribe_Controller, there I define what parameters are sent to MailChimp for the mailing list , here is the error log from $heroku run rails console.

/app/app/controllers/subscribe_controller.rb:11:in `private': nil is not a symbo  l (TypeError)          from /app/app/controllers/subscribe_controller.rb:11:in `<class:Subscrib  eController>'          from /app/app/controllers/subscribe_controller.rb:1:in `<top (required)>  '          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `require'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `block in require'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:240:in `load_dependency'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `require'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:360:in `require_or_load'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:317:in `depend_on'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:233:in `require_dependency'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:472:in `block (2 levels) in eager_load!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:471:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:471:in `block in eager_load!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:469:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:469:in `eager_load!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/engin  e.rb:346:in `eager_load!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/appli  cation/finisher.rb:56:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/appli  cation/finisher.rb:56:in `block in <module:Finisher>'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:30:in `instance_exec'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:30:in `run'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:55:in `block in run_initializers'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:150:in `block in tso  rt_each'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:183:in `block (2 lev  els) in each_strongly_connected_component'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2 lev  els) in each_strongly_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2 lev  els) in each_strongly_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2 lev  els) in each_strongly_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:219:in `each_strongl  y_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in eac  h_strongly_connected_component_from'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `tsort_each_child'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_strongl  y_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in eac  h_strongly_connected_component_from'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `tsort_each_child'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_strongl  y_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in eac  h_strongly_connected_component_from'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:44:in `tsort_each_child'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_strongl  y_connected_component_from'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:182:in `block in eac  h_strongly_connected_component'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each_strongl  y_connected_component'          from /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/initi  alizable.rb:54:in `run_initializers'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/appli  cation.rb:352:in `initialize!'          from /app/config/environment.rb:5:in `<top (required)>'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `require'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `block in require'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:240:in `load_dependency'          from /app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.2.7.1/lib/active  _support/dependencies.rb:274:in `require'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/appli  cation.rb:328:in `require_environment!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/comma  nds/commands_tasks.rb:142:in `require_application_and_environment!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/comma  nds/commands_tasks.rb:67:in `console'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/comma  nds/commands_tasks.rb:39:in `run_command!'          from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.2.7.1/lib/rails/comma  nds.rb:17:in `<top (required)>'          from /app/bin/rails:4:in `require'          from /app/bin/rails:4:in `<main>'  

here is the log from the production server:

2016-09-21T14:53:45.788249+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.ifurniture.pe request_id=4e9cd392-23bb-4160-8f2b-e9886cf25016 fwd="190.234.106.227" dyno= connect= service= status=503 bytes=  

this is the Subscribe_Controller.rb file..

class SubscribeController < ApplicationController    def create      logger.info "suscripcion #{params.inspect}"      user = user_params(params)      MailchimpWrapper.subscribe(user, params[:group_name], params[:group])      redirect_to '/gracias'      rescue Mailchimp::Error => e        logger.error "ERROR mailchimp #{e.message} #{params.inspect}"      end      private def user_params(params)      user = {        email: params[:email].try(:downcase),        first_name: params[:first_name].try(:titleize),        last_name: params[:last_name].try(:titleize),        city: params[:city].try(:titleize),        phone: params[:phone],        comment: params[:comment].try(:titleize)      }      user    end  end  

I'll be attentive to your answers.

Rails - bundle error

Posted: 21 Sep 2016 07:55 AM PDT

I created a new project, run all basic commands and everything worked fine. But now I tried to add some gems and when I run bundle, I get the error:

/usr/lib/ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find bundler (>= 0) amongst [bundler-unload-1.0.2, did_you_mean-1.0.0, executable-hooks-1.3.2, gem-wrappers-1.2.7, minitest-5.8.3, net-telnet-0.1.1, power_assert-0.2.6, rake-10.4.2, rubygems-bundler-1.4.4, rvm-1.11.3.9, test-unit-3.1.5] (Gem::LoadError)  

I'm using ruby 2.3.1 on that project (checked on rvm list), so I think it's wrong that it try to run on /usr/lib/ruby/1.9.1/

Anybody know the reason?

Query appears to work in console but cannot get data in view

Posted: 21 Sep 2016 08:14 AM PDT

I am trying to use this query

pages_controller.rb

# GET /pages/1  # GET /pages/1.json  def show    @page = Page.where('category_title = ?', params[:category_title]).where('slug = ?', params[:slug])  end  

routes.rb

match ':category_title/:slug', :via => 'get', :controller => :pages, :action => :show  

I get an error in the view of "undefined method' for the properties of that page (id, slug, etc.). The query looks right to me in the console but when the page loads it is not actually getting any data.

enter image description here

If I print out a count it comes back as 1, which is correct.

enter image description here

I have looked at a few posts about creating named routes and thought I had it, but clearly I am missing something.

Any help with what part of this I am missing would be greatly appreciated.

Rails - how to delimit a reserved sql keyword

Posted: 21 Sep 2016 07:43 AM PDT

I am working on a sort routine that worked in other apps/sections. However, it appears that the resulting query doesn't work because the associated table is named user which apparently is a reserved SQL word. The fix is to have the query reference '[user].name' instead of user.name

The line that is causing the problem is

   @workflows = @workflows.includes(:user).order(params[:sort] + ' ' + params[:direction])  

The error I get is

ActiveRecord::StatementInvalid in Workflows#index  Showing C:/Users/cmendla/RubymineProjects/product_development/app/views/workflows/index.html.erb where line #14 raised:    TinyTds::Error: Cannot call methods on nvarchar.: EXEC sp_executesql N'SELECT [pd].[workflows].[id] AS t0_r0, [pd].[workflows].[title] AS t0_r1, [pd].[workflows].[user_id] AS t0_r2, [pd].[workflows].[created_at] AS t0_r3, [pd].[workflows].[updated_at] AS t0_r4, [pd].[users].[id] AS t1_r0, [pd].[users].[login] AS t1_r1, [pd].[users].[group_strings] AS t1_r2, [pd].[users].[name] AS t1_r3, [pd].[users].[ou_strings] AS t1_r4, [pd].[users].[email] AS t1_r5, [pd].[users].[created_at] AS t1_r6, [pd].[users].[updated_at] AS t1_r7 FROM [pd].[workflows] LEFT OUTER JOIN [pd].[users] ON [pd].[users].[id] = [pd].[workflows].[user_id]  ORDER BY user.name asc'  Rails.root: C:/Users/cmendla/RubymineProjects/product_development    Application Trace | Framework Trace | Full Trace  app/views/workflows/index.html.erb:14:in `_app_views_workflows_index_html_erb__557116297_91831440'  Request  

The url looks like http://localhost:3000/workflows?direction=asc&sort=user.name

Can I modify the @workflows = line so that it will put user in []'s ?

Rails 5 - CanCan

Posted: 21 Sep 2016 07:40 AM PDT

I would like to know if CanCan gem (or cancancan) works fine with rails 5. On http://www.ready4rails.net/gems/cancan, it is flaged as "unknown"... I'm about to start a new project and it's really relevant. Thanks!

Solr won't start reindexing -- Not found

Posted: 21 Sep 2016 07:24 AM PDT

I've tried different approaches to get solr to work, in particular, these rake sunspot:reindex rake aborted! RSolr::Error::Http - 404 Not Found, but I've ended up with this yet:

 $ bundle exec rake sunspot:reindex  => Solr server started    rake aborted!  RSolr::Error::Http: RSolr::Error::Http - 404 Not Found  Error:     Not Found    URI: http://127.0.0.1:8983/solr/default/update?wt=ruby  Request Headers: {"Content-Type"=>"text/xml"}  Request Data: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><delete><query>type:ActsAsTaggableOn\\:\\:Tag</query></delete>"  

How to fix it?

get info from third table with association

Posted: 21 Sep 2016 07:51 AM PDT

I have a Service model. every service can be given by several users, so I have a User model.

I have a connection table: services_users with a ServiceUser model

p.s: this table has user_id, service_id and blah_id columns

Now, I want to write: service.users and get all users from users table for a given service.

How would I write this in the model? service.users gives me a query from services_users, which is the connecting table, but I want the results from users table.

Rails Not able to save data, association

Posted: 21 Sep 2016 07:41 AM PDT

I'm doing a parking permit website. The problem I met is that I'm not able to save my data to the PERMIT database which associated with the USER database. The problem i think is I didn't bring the user to the permit(Maybe i missed something). I found out the error when I trying to save from Permit.errors.full_messages is ["User must exist"]. Any help is appreciated, Thank you!

Schema.rb

ActiveRecord::Schema.define(version: 20160920143651) do      create_table "permits", force: :cascade do |t|      t.string   "vehicle_type"      t.string   "name"      t.string   "studentid"      t.string   "department"      t.string   "carplate"      t.string   "duration"      t.date     "permitstart"      t.date     "permitend"      t.integer  "user_id"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false      t.index ["user_id"], name: "index_permits_on_user_id"    end      create_table "users", force: :cascade do |t|      t.string   "name"      t.string   "email"      t.datetime "created_at",      null: false      t.datetime "updated_at",      null: false      t.string   "password_digest"      t.integer  "user_type"    end    end  

Create_permit.rb

class CreatePermits < ActiveRecord::Migration[5.0]    def change      create_table :permits do |t|        t.string :vehicle_type        t.string :name        t.string :studentid        t.string :department        t.string :carplate        t.string :duration        t.date :permitstart        t.date :permitend        t.references :user, foreign_key: true          t.timestamps      end      add_index :permits, :user_id    end  end  

Permit_controller

class PermitsController < ApplicationController    before_action :set_permit, only: [:show, :destroy]    def index      @permits = Permit.all    end      def new      @permits = Permit.new    end      def create      @permits = Permit.new(permit_params)          if @permits.save          redirect_to @permits        else          redirect_to contact_path        end      end      def destroy      Permit.destroy_all(user_id: 1)      respond_to do |format|        format.html { redirect_to users_url, notice: 'Permit was successfully canceled.' }        format.json { head :no_content }      end    end      def show      @permits = Permit.find(params[:id])    end      def update      respond_to do |format|        if @permits.update(user_params)          format.html { redirect_to @user, notice: 'Permit was successfully updated.' }          format.json { render :show, status: :ok, location: @user }        else          format.html { render :edit }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end      private    # Use callbacks to share common setup or constraints between actions.    def set_permit      @permits = Permit.find(params[:id])    end      # Never trust parameters from the scary internet, only allow the white list through.    def permit_params      params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration, :permitstart, :permitend)    end  end  

user.rb

class User < ApplicationRecord    has_many :permits    has_secure_password  end  

Permit.rb

    class Permit < ApplicationRecord      belongs_to :user      end    permit/new.html.erb  <% provide(:title, 'New Permit') %>  <h1>Permit Application</h1>    <div class="row">    <div class="col-md-6 col-md-offset-3">      <%= form_for(@permits) do |f| %>            <%= f.label :"Vehicle" %>          <%= f.text_field :vehicle_type, class: 'form-control' %>            <%= f.label :"License Plate" %>          <%= f.text_field :carplate, class: 'form-control' %>            <%= f.label :"Student ID" %>          <%= f.text_field :studentid, class: 'form-control' %>            <%= f.label :name %>          <%= f.text_field :name, class: 'form-control' %>            <%= f.label :"Department of applicant" %>          <%= f.text_field :department, class: 'form-control' %>            <%= f.label :permit_start %>          <%= f.date_select :permitstart, class: 'form-control' %>            <%= f.label :permit_end %>          <%= f.date_select :permitend,  class: 'form-control'  %>              <%= f.submit "Submit", class: "btn btn-primary" %>      <% end %>    </div>  </div>  

How can I authenticate a user with admin attribute for rails_admin with devise

Posted: 21 Sep 2016 07:15 AM PDT

I am fairly new to ruby on rails. I habe set up a mysql database, connected it with a rails app, installed the devise gem and rails_admin gem. So far so good, everything works as it should. Now I also added a usergroup attribute to the users table, to identify different user group. Only "admin" should be allowed to access rails admin. I already use the predefined commands in /app/config/initializers/rails_admin.rb

   RailsAdmin.config do |config|      ### Popular gems integration      ## == Devise ==     config.authenticate_with do       warden.authenticate! scope: :admin     end     config.current_user_method(&:current_user)      ## == Cancan ==    # config.authorize_with :cancan      ## == Pundit ==    # config.authorize_with :pundit      ## == PaperTrail ==    # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0      ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration      ## == Gravatar integration ==    ## To disable Gravatar integration in Navigation Bar set to false    # config.show_gravatar true      config.actions do      dashboard                     # mandatory      index                         # mandatory      new      export      bulk_delete      show      edit      delete      show_in_app        ## With an audit adapter, you can add:      # history_index      # history_show    end  end  

This works so far that you have to login before you can access the page. Now there also has to be a check wether current_user.usergroup = 'admin'.

In devise this is also explained as one possible method to 'handle' usergroups. https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-Role

But I am pretty confused how to insert this check into the config that way.

Rails 4 add nested values from static fields

Posted: 21 Sep 2016 06:57 AM PDT

I'm using the cocoon gem to add some nested values to my form. So far everything works fine. Now I would like to change the form and have a single row of input fields and when the user clicks "add", the data in the input fields is added to the nested fields collection and shown below the input fields. Here is a simple mockup of what I'm trying to accomplish:

Simple mockup

I'm pretty new to rails and I'm not sure how to accomplish this. What I have done so far is to create three virtual attributes, one for Area, Product and Quantity. This takes care of the static data entry fields on the form but I am unsure how to add the data to the dynamic portion of the form. I can't figure out how to pass the data to cocoon. How can I pass the data to cocoon and create the nested item? Is there a gem that would work better for this scenario or a better overall approach?

Your help is greatly appreciated.

How to convert this curl command to httparty in Rails? Using Orange SMS Api

Posted: 21 Sep 2016 06:50 AM PDT

I'm trying to use Orange SMS API, I read how to use it here.

I want to use this api from Rails application.

I want to convert this curl command to httparty code.

curl -X POST \  -H "Authorization: {authorization_header}" \  -d "grant_type=client_credentials" \  https://api.orange.com/oauth/v2/token  

I searched for many solutions, but all failed :(

here's the last try

HTTParty.post(        "https://api.orange.com/oauth/v2/token",        headers: {           "Content-Type" => "application/x-www-form-urlencoded",           "Authorization" => "Basic {authorization_header}",          "Accept" => "application/json"        },        body: {          :grant_type => "client_credentials"        }.to_json      )  

but I receive this error:

504 Gateway Time-out

\nThe server didn't respond in time.\n\n", @response=#, @headers={"date"=>["Wed, 21 Sep 2016 13:35:37 GMT"], "cache-control"=>["no-cache"], "content-type"=>["text/html; charset=UTF-8"], "connection"=>["close"], "transfer-encoding"=>["chunked"]}>

irb(main):073:0>

I also tried this way

       access_token = HTTParty.post(           "https://api.orange.com/oauth/v2/token",           headers: { "Content-Type" => "application/x-www-form-urlencoded", "Authorization" => "Basic {authorization_header}"},           query: { "grant_type" => "client_credentials" }         )  

but I get this error:

=> #"invalid_grant", "error_description"=>"The paramater grant_type is not valid."}, @response=#, @headers={"date"=>["Wed, 21 Sep 2016 13:14:18 GMT"], "host"=>["ope-apigee-private"], "content-type"=>["application/json"], "authorization"=>["Basic cWVnaUJlR0xhcndaYzZ0R1dtS1JqUFE2d0FBOVNEWW46SFJ1SGFURUJlOHR2aHlTOA=="], "x-forwarded-for"=>["213.181.226.205, 192.168.70.3", "192.168.9.45"], "x-forwarded-host"=>["api.orange.com"], "x-forwarded-server"=>["OPOPECBALLAP04"], "content-length"=>["86"], "connection"=>["close"]}>

I don't know how to use it I read the official way and it worked using Curl but I can't do it in Rails.

Rails unable to autoload constant user_type

Posted: 21 Sep 2016 06:56 AM PDT

Im buliding an app with users model which can have different privileges, described by user_types model (id and type as a string). As I am running rails test, I am getting error

LoadError: Unable to autoload constant User_type, expected app/models/user_type.rb to define it  

Here is my model:

class UserType < ActiveRecord::Base      belongs_to :user      validates :type, presence: true, length: { maximum: 100 }  end  

Below is the controller and test file

class UserTypeController < ApplicationController      def index          @user_type = User_type.all      end       def new          @user_type = User_type.build(user_type_params)      end      private      def user_type_params          params.require(:user_type).permit(:type)      end  end  

Testing model:

require 'test_helper'    class UserTypeTest < ActiveSupport::TestCase    # test "the truth" do    #   assert true    # end    def setup      @user_type = User_type.new(id:2,type:"test")    end    test "is_valid" do      assert @user_type.valid?    end    end  

I wanted to do some basic "is_valid" test and I got an error described above. I have also dropped last model "user_type" and created it as "UserType" but It didn't work.

How can I serve static content in my Rails 2.3 application using Nginx?

Posted: 21 Sep 2016 07:04 AM PDT

The users of this legacy application I'm supporting can run reports, and the reports are put in a directory structure like:

/customers/<account number>/output/  

Where <account number> is there 5-digit account number.

nginx is showing 404 on these files.

But not on all of them! There appears to be no rhyme or reason as to what is downloading and what isn't.

I have carefully checked permissions and ownership of both the files and the directory paths. There is zero difference.

Ruby on Rails 5 - stable version?

Posted: 21 Sep 2016 06:28 AM PDT

I'm going to work on a new project and I would like to know the best rails version to use. I see on the main site the "Latest version — Rails 5.0.0.1 released August 11, 2016", but as long as I knew, Rails 5 was in beta phase. Is that version stable to use? Thanks

caching in-between backend and frontend application

Posted: 21 Sep 2016 06:13 AM PDT

I am running a Rails API and ReactJS SPA architecture for my site. Are there any solid solutions for caching so that the number of client-side requests to the Rails API is restricted through an intermediary cache? Looking for something simple and efficient. Thank you!

So this is what I have in mind:

Client-side data request (reactjs application) --> cache (independent cache server) --> cache server restricts # of requests to API (ie a time based expiration, etc) --> accesses API if necessary to get new data

Heroku is serving old assets for Rails 5 application

Posted: 21 Sep 2016 07:02 AM PDT

I've deployed a new version of a Rails 5 app on Heroku, running on cedar-14 stack. It didn't precompile while deploying, so I did heroku run rake assets:precompile manually. Still, I can see it includes old assets while requiring css and js files.

My files are in app/assets so it's not possible that directory isn't in assets compile path.

My config on application.rb and production.rb:

config.assets.compile = true    # I checked the environment variable, it responds to 'enabled',  # which would return true for the option.  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?    # Which I changed to expire old assets.  config.assets.version='1.1'  

I tried these, but they didn't work:

  • $ heroku restart
  • $ heroku run rake assets:precompile
  • $ heroku run rake assets:clobber

The weird thing with these is that they do not affect assets in heroku server, which I checked with $ heroku run ls public/assets. Even after $ rake assets:precompile, even though it says this:

WRITING /app/public/assets/application-{VERY_LONG_HASH}.js  WRITING /app/public/assets/application-{VERY_LONG_HASH}.js.gz  WRITING /app/public/assets/application-{VERY_LONG_HASH}.css  WRITING /app/public/assets/application-{VERY_LONG_HASH}.css.gz  

when I peek with the $ heroku run ls public/assets, I still see old assets staying there.

EDIT: I solved it by deleting all the local assets in public/assets, recompiling them with $ rake assets:clean && rake assets:precompile and including these assets in my git repository. Here is one concern:

Shouldn't heroku be responsible of compiling my assets on the fly? I think I shouldn't be compiling my assets everytime I deploy my application. Thanks.

Unexpected error while processing request: invalid byte sequence in UTF-8 #

Posted: 21 Sep 2016 06:29 AM PDT

when enable rack-mini-profiler gem, it gives error

Unexpected error while processing request: invalid byte sequence in UTF-8  

using

 Rails v4.0.6     rack-mini-profiler 0.10.1     Ruby 2.2.0  

only happen if enable rake-mini-profiler, otherwise application working fine.

backtrace:

Unexpected error while processing request: invalid byte sequence in UTF-8    /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-mini-profiler-0.10.1/lib/mini_profiler/client_settings.rb:24:in `split'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-mini-profiler-0.10.1/lib/mini_profiler/client_settings.rb:24:in `initialize'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-mini-profiler-0.10.1/lib/mini_profiler/profiler.rb:153:in `new'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-mini-profiler-0.10.1/lib/mini_profiler/profiler.rb:153:in `call'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/engine.rb:511:in `call'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/application.rb:97:in `call'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-1.5.5/lib/rack/content_length.rb:14:in `call'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/connection.rb:86:in `block in pre_process'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/connection.rb:84:in `catch'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/connection.rb:84:in `pre_process'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/connection.rb:53:in `process'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/connection.rb:39:in `receive_data'  /home/aa/.rvm/gems/ruby-2.2.0/gems/eventmachine-1.0.8/lib/eventmachine.rb:193:in `run_machine'  /home/aa/.rvm/gems/ruby-2.2.0/gems/eventmachine-1.0.8/lib/eventmachine.rb:193:in `run'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/backends/base.rb:73:in `start'  /home/aa/.rvm/gems/ruby-2.2.0/gems/thin-1.6.4/lib/thin/server.rb:162:in `start'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-1.5.5/lib/rack/handler/thin.rb:16:in `run'  /home/aa/.rvm/gems/ruby-2.2.0/gems/rack-1.5.5/lib/rack/server.rb:264:in `start'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/commands/server.rb:84:in `start'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/commands.rb:76:in `block in <top (required)>'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/commands.rb:71:in `tap'  /home/aa/.rvm/gems/ruby-2.2.0/gems/railties-4.0.6/lib/rails/commands.rb:71:in `<top (required)>'  bin/rails:4:in `require'  bin/rails:4:in `<main>'  

I'm not sure, i think this error keep coming after 'Slim-Rails' gem

How reduce lines of Rails ApplicationHelper

Posted: 21 Sep 2016 06:42 AM PDT

My ApplicationHelper have more than 100 lines, and the Rubocop alert me that "Module has many lines". What the good practices for solve this? Divide it in another helper? Create a lib?

Designing a Search bar and retrieving data from database rails4

Posted: 21 Sep 2016 06:12 AM PDT

Now i am tried by following to this article http://www.rymcmahon.com/articles/2

My product.rb file is

 class Product < ActiveRecord::Base     def self.search(search)       where("name LIKE ?","%#{search}%")     end   end  

my index file is

Data

 <%= form_tag(products_path, :method => "get") do %>     <%= text_field_tag :search, params[:search], placeholder: "products" %>     <%= submit_tag "Search", :name => nil %>   <% end %>  

my index method is

def index    @product = Product.all   if params[:search]    @recipes = Product.search(params[:search]).order("created_at DESC")   else    @recipes =Product.all.order("created_at DESC")   end  end  

But it didn't filtering the data my output is:

 dinesh 200 2016-09-21 06:10:40 UTC   reddyc 300 2016-09-21 06:16:31 UTC   Goods 200 2016-09-21 09:33:56 UTC  

How to use polymer routes (app-routes) in rails?

Posted: 21 Sep 2016 05:27 AM PDT

I am using polymer with rails and i am stuck while using routes. is there any gem that contain app-routes of polymer.

I am using these gem for support 'polymer-rails' 'polymer-elements-rails' 'polymer-iron-rails'

and need routes information is there any ?

Prevent adding inputs with cocoon

Posted: 21 Sep 2016 05:05 AM PDT

I'm using cocoon for a nested form that accepts different kind of files.

Everytime I click on the button, a new input is created, and once the user selects a file, the preview appears inside of the input.

BUT, if for some reason, my user cancels the file upload (by clicking on the usual 'cancel' button, in the file selection window), the extra input is still added, with nothing in it, and when the form is submitted, the empty input is still processed, resulting in an extra, unnecessary record.

Is there a way to prevent this behaviour, so that if the file selection is cancelled, the extra input is destroyed ?

Rails unit test - undefined method 'users'

Posted: 21 Sep 2016 05:48 AM PDT

I've been trying to figure out how to test, but nothing seems to solve my issue. Every time I try to run any test, I get this error:

NoMethodError: undefined method `users' for #<#<Class:0x00560775e00768>:0x00560775e00470>  

How i run my test inside a model: ruby test/models/plan_test.rb

I am trying to run the most basic test (the one Rails gave me as an example), so it is not linked to any model/fixture. My model:

require File.expand_path("../../test_helper", __FILE__)    class PlanTest < ActiveSupport::TestCase    test "the truth" do      assert true    end  end  

I have created an empty test database, too, and when I try to add the fixtures inside the database, I get the same error.

Thank you for looking :)

Edit: Trace on the fixture command(rake db:fixtures:load RAILS_ENV=test --trace):

[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.  ** Invoke db:fixtures:load (first_time)  ** Invoke environment (first_time)  ** Execute environment  ** Invoke db:load_config (first_time)  ** Execute db:load_config  ** Execute db:fixtures:load  rake aborted!  NoMethodError: undefined method `users' for #<#<Class:0x005555661d3920>:0x005555661d3830>  (erb):4:in `get_binding'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/2.2.0/erb.rb:863:in `eval'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/2.2.0/erb.rb:863:in `result'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixture_set/file.rb:42:in `render'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixture_set/file.rb:33:in `rows'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixture_set/file.rb:24:in `each'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:760:in `block (2 levels) in read_fixture_files'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixture_set/file.rb:15:in `open'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:759:in `block in read_fixture_files'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:758:in `each'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:758:in `each_with_object'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:758:in `read_fixture_files'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:590:in `initialize'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:514:in `new'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:514:in `block (2 levels) in create_fixtures'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:511:in `map'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:511:in `block in create_fixtures'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:288:in `disable_referential_integrity'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/fixtures.rb:508:in `create_fixtures'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5/lib/active_record/railties/databases.rake:206:in `block (3 levels) in <top (required)>'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `call'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:80:in `block in run'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'  /home/ioana/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'  /home/ioana/.rbenv/versions/2.2.3/bin/rake:23:in `load'  /home/ioana/.rbenv/versions/2.2.3/bin/rake:23:in `<main>'  Tasks: TOP => db:fixtures:load  

Part of my user fixture (all of them have the same structure):

one:    email: ioana1@ioana.com    name: Ioana1    password: MyString    verified: 1    token: MyString    remember_token: MyString    plan_id: <%= plan(:p0).id %>    subscription_id: 1    subscription_next_bill_date:    email_hash: 1    referred_by_user_id: <%= users(:two).id %>    subscription_status: deleted    three:    email: ioana3@ioana.com    name: Ioana3    password: MyString    verified: 1    token: MyString    remember_token: MyString    plan_id: <%= plan(:p1).id %>    subscription_id: 1    subscription_next_bill_date: 2016-08-04    subscription_update_url: MyString    subscription_cancel_url: MyString    email_hash: 1    subscription_registration_date: 2016-07-04    subscription_status: active  

Get selected value of dropdown with capybara

Posted: 21 Sep 2016 06:12 AM PDT

I'm trying to get the selected value of a dropdown box with next code:

scenario 'USA as default country' do    expect(page).to have_select('report_country_code', selected: 'United States')  end  

Html for this field is the next:

<select class="form-control country required" name="report[country_code]" id="report_country_code">    <option value="US">United States</option>    ....    ....    <option value="ZW">Zimbabwe</option>  </select>  

And the error looks like:

expected to find select box "report_country_code" with "United States" selected but there were no matches. Also found "United States .... Zimbabwe", which matched the selector but not all filters.  

Active model serializer nested association nil issue

Posted: 21 Sep 2016 07:02 AM PDT

I've the following associations

class User < ActiveRecord::Base    has_one :book   end    class Book < ActiveRecord::Base    has_many :pages  end  

And my serializers look like:

user_serializer.rb

class UserSerializer < ActiveModel::Serializer    ...    has_one :book, serializer: BookSerializer    end  

book_serializer.rb

class BookSerializer < ActiveModel::Serializer    ...    has_many :pages  end  

Now, when I try to serialize a user object which has no book, it raises an error saying undefined method pages for nil class. How can I add a condition that allow serializing book only if it is not nil?

How to make a pre-emptive basic authentication call using savon client in ruby?

Posted: 21 Sep 2016 04:12 AM PDT

I am doing the following code in savon but unable to do as it requires pre-emptive authorization. I have verified in soapUI but unable to run in savon. Could somebody help?

client = Savon.client(ssl_verify_mode: :none) do    wsdl '/Users/sp/jda_notifications/TransportationManagerService.wsdl'    endpoint 'http://localhost:8088/webservices/services/TransportationManager'    basic_auth('VENTURE', 'VENTURE')  end  

AngularJs escape bracket in name tag?

Posted: 21 Sep 2016 04:25 AM PDT

There is a Rails Project, a form for user login with devise, but there is problem while use ng-show

  <%= f.email_field :email,class: "form-control", autofocus: true, placeholder: "input your email",required: true,"ng-model"=> "user[email]" %>  </div>        <div style="color:red;" ng-show="myForm.user[email].$dirty && myForm.user[email].$invalid">          <p ng-show="myForm.user[email].$error.required" style="float: left">email can't be blank</p>          <p ng-show="myForm.user[email].$error.email" style="float: left">email is not correct</p>        </div>  

myForm.user[email] seems can't get object property, How can we make this line work without change input's name.

ng-show="myForm.user[email].$error.required"  

In the other words,how can we escape[]

Recover single piece/table of data from rollback on heroku postgres

Posted: 21 Sep 2016 03:44 AM PDT

Someone accidentally wiped a single piece of data from my heroku postgres db.

I'm looking at the rollback function that allows us to roll back the entire db to a previous point in time. However, some of my tables have millions of rows, whereas the table in question has a hundred or two. Is there a way to just provide a rollback of the individual table so I can get that piece of data (a string)?

userid in params but unable use it in controller?

Posted: 21 Sep 2016 03:45 AM PDT

this is my view file i am sending the userid in parameters,

  <%= form_for :user, :url=>{:action=>'update'},:method=>"get",:html=>{:class=>'form-horizontal'} do |f|%>        <div class="form-group">          <label class="col-md-4 control-label" for="textinput">Admin</label>          <div class="col-md-4">          <%= f.radio_button :is_admin, 'true', :checked => true %> Yes          <%= f.radio_button :is_admin, 'false' %> no          <%= f.hidden_field :userid, value: @id %>          </div>        </div>        <%= f.submit ('save') %>      <% end %>  

but when i try to access it in my controller i get following error (record not found):

this is the error

I am finding user in my controller method like this:

def update      @users = User.all      @uid = params[:userid]       @users = User.find_by_id!(@uid)                  if @users.update_attributes(user_params)                    flash[:notice] = "User updated successfully."                    redirect_to :action=>'view'                  else                    flash[:notice] = "Error while updating user."                    render 'edit'                  end             end      private        def user_params        params.require(:user).permit(:is_admin,:is_member)      end  end  

No comments:

Post a Comment