Monday, May 23, 2016

RSpec controller spec is acting like a request spec | Fixed issues

RSpec controller spec is acting like a request spec | Fixed issues


RSpec controller spec is acting like a request spec

Posted: 23 May 2016 07:08 AM PDT

  • Rails 5.0.0.rc1
  • rspec-core@a99ff26
  • rspec-rails@052206f

I have a controller spec that looks roughly like this:

require "rails_helper"    RSpec.describe InquiriesController, type: :controller do    describe "#create" do      let(:inquiry_attributes) { attributes_for(:inquiry) }        before do        post :create, inquiry: inquiry_attributes      end        it "whatever" do        expect(2).to be 2      end    end  end  

This lives in spec/controllers/inquiries_controller_spec.rb, so RSpec should not be inferring that it's a request spec based on its location.

When I run this spec, I get the following error:

1) InquiriesController#create whatever     Failure/Error: post :create, inquiry: inquiry_attributes       URI::InvalidURIError:       bad URI(is not URI?): create       # /Users/spetryk/.gem/ruby/2.3.1/gems/rack-test-0.6.3/lib/rack/test.rb:193:in `env_for'       # /Users/spetryk/.gem/ruby/2.3.1/gems/rack-test-0.6.3/lib/rack/test.rb:66:in `post'  

Hmm, it seems that post is coming from Rack. Not sure why. Here's my spec_helper and rails_helper:

spec_helper.rb

RSpec.configure do |config|    config.expect_with :rspec do |expectations|      expectations.include_chain_clauses_in_custom_matcher_descriptions = true    end      config.mock_with :rspec do |mocks|      mocks.verify_partial_doubles = true    end      config.filter_run focus: true    config.run_all_when_everything_filtered = true  end  

rails_helper.rb

ENV["RAILS_ENV"] ||= "test"  require File.expand_path("../../config/environment", __FILE__)    abort("The Rails environment is running in production mode!") if Rails.env.production?    require "spec_helper"  require "rspec/rails"  Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }    ActiveRecord::Migration.maintain_test_schema!    RSpec.configure do |config|    config.use_transactional_fixtures = true      # Yes, I've tried removing this line    config.infer_spec_type_from_file_location!      config.filter_rails_from_backtrace!      config.include Rails.application.routes.url_helpers    config.include FactoryGirl::Syntax::Methods  end  

My InquiriesController lives in app/controllers/inquiries_controller.rb, is not underneath a module, and the route is wired up correctly (I verified this by manually visiting it and verifying that it works). The method is indeed named create and I've done this successfully with other projects.

Carrierwave - storing file in dynamic public folder

Posted: 23 May 2016 07:05 AM PDT

I am using Carrierwave 0.5.8 for storing uploaded file. In my app users can upload any file. So I have to maintain folders like "public/uploads/1/", "public/uploads/2/", where 1, 2...etc will be user ids, and these folders will contain files uploaded by user in his corresponding id folder.

So I was reading the doc at : Carrierwave github repo and it has some code like :

u = User.new  u.avatar = params[:file] # Assign a file like this, or    # like this  File.open('somewhere') do |f|     u.avatar = f  end    u.save!  

My question is, what is the File.open("Somewhere") ? Where is the second parameter like "r" or "w" ? Isn't it vague for the beginner to understand?

"Somewhere" can't be directory because it is "File.open", it will look for the file. If it is a file then what path should I give? I don't know the name of file beforehand. We can get the filename from the file object parama[:file]. Then it means I have to do something like this:

File.open(Rails.root.join('public', 'uploads/', @user.id, filename), "w") do |file|    u.avatar = file  end  # I am able to achieve with this what I want to do  

Right?

That is fine, But there is one another setting/action in file_uploader.rb :

# Override the directory where uploaded files will be stored.  # This is a sensible default for uploaders that are meant to be mounted:    def store_dir    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"  end  

So as per the document it will store the files in that particular folder, based on model.id. But then I am confused what I am doing with File.open action?

On top of the documentation there is some more code :

# You can use your uploader class to store and retrieve files like this:  uploader = AvatarUploader.new  uploader.store!(my_file)  

I guess store_dir action works with this .store action. But when I use this. The file gets stored in tmp directory in image folder. And view throws an error Called id for nil, model.id something like this from store_div action (Even if it doesn't throw error, it is not saving the file in folder).

Note: I am just using it as learning purpose.

I am confused with which thing doing what: User.new with file.open or AvatarUploader.new with Uploader.store (Which code when to use and where to use). Can anybody explain?

Need ActiveRecord query to find parent that has specific child record along with others

Posted: 23 May 2016 07:04 AM PDT

I'm using Ruby on Rails and Postgres and I have three tables: Event, Speaker, and Event_Speaker (the last of which enables a two-way has_many, through relationship between Event and Speaker).

On an individual speaker's show view, I'm trying to display not only all of the events featuring that speaker, but also the count of how many events feature only that speaker (versus events featuring that speaker along with one or more others).

I can't seem to come up with an ActiveRecord query that is able to accomplish this latter part. Any ideas?

Rails Asset Pipeline, SCSS, and Z-Index

Posted: 23 May 2016 06:45 AM PDT

I have a .scss stylesheet that is being processed through the Rails Asset Pipeline. The code is as follows:

.new-email {    .ui.dropdown {      z-index: 101 !important;    }  }  

When I run this in development, it get compiled to :

.new-email .ui.dropdown {    z-index: 101 !important;  }  

However, when I deploy to our production environment with

rake assets:precompile  

It compiles to

.new-email .ui.dropdown{z-index:2!important}  

What's going on? Is there a compass setting that I don't know about or something is SASS or the asset pipeline configuration that tries to be smart about z-indexes and intelligently reduce them?

Seems like a smart thing to do, but in this case, I'd like to disable the functionality...

I want to use ES6 with Rails

Posted: 23 May 2016 06:42 AM PDT

I want to use ES6 in a Ruby on Rails application. Earlier I was using CoffeeScript and it was compiled to JavaScript on the fly in the Rails application. Similarly I want use ES6 as source and ES5 in the browser. I do not want to use babel to pre-compile the es6 files into es5. I searched for Babel and Rails but did not find any good gems.

End of file reached Error in controller while hitting a web service using Httparty gem

Posted: 23 May 2016 06:39 AM PDT

Please help me, I am sending a get request using httparty, sometime it give End of file error, and sometimes it works file without any problem, I am unable to find problem, please help me to resolve the issue.

Rails 4 Query Interface WHERE IN

Posted: 23 May 2016 07:18 AM PDT

I can't seem to figure out how to write the following simple SQL using Rails Active Record Query Interface.

SELECT *   FROM product_sales   WHERE (product_location_id, net_sale)   IN   (     SELECT product_location_id, MAX(net_sale)    FROM product_sales    GROUP BY product_location_id  )   AND (sale_date BETWEEN '2016-05-01' AND '2016-05-31');  

Note: I've looked at the following link. However, it only specifies a single column in the outer WHERE clause, whereas I need two.

Link: subqueries in activerecord

Thanks for any assistance.

UPDATE

Models

[ProductSale]

references :product_location, index: true, foreign_key: true  decimal :net_sale, precision: 16, scale: 6  date :sale_date  

[ProductLocation]

references :product, index: true, foreign_key: true  etc...  

Relations

ProductSale -> belongs_to :product_location  ProductLocation -> has_many: product_sales  

Please note my DB is in MySQL.

Windows, Ec2ServerCreate - Cannot set JSON attributes when running knife from Rails application

Posted: 23 May 2016 06:29 AM PDT

I am able to launch new instance at AWS from Ruby on Rails application (Chef::Knife::Ec2ServerCreate.new()). Works fine till I try to set JSON attributes. When I set them from command line and invoke knife.bat, it works. Looking at ec2_server_create shows that command line option --json-attributes is mapped to symbol :json_attributes. I tried to set it using following code:

Chef::Config[:knife][:json_attributes] = "{'NodeName' : 'Node001'}"  

and I get error:TypeError (no implicit conversion of Symbol into Integer): As soon as I comment this single line, instance is created, registered with chef server and recipe is running. Any suggestion how to set json attributes of first chef-client run? PS Sample code shows constant value for attribute, but actual value would be dynamically created.

Find key value pair in PostgreSQL's HSTORE

Posted: 23 May 2016 07:05 AM PDT

Given a table games and column identifiers, whose type is HSTORE:

| id | name             | identifiers                        |  |----|------------------|------------------------------------|  | 1  | Metal Gear       | { sku: 109127072, ean: 512312342 } |  | 2  | Theme Hospital   | { sku: 399348341 }                 |  | 3  | Final Fantasy    | { ean: 109127072, upc: 999284928 } |  | 4  | Age of Mythology | { tbp: 'a998fa31'}                 |  | 5  | Starcraft II     | { sku: 892937742, upc: 002399488 } |  

How can I find if a given set of key-value pairs has at least one match in the database?

For example, if I supply this array: [ {sku: 109127072 }, { upc: 999284928 } ], I should see:

| id | name           | identifiers                        |  |----|----------------|------------------------------------|  | 1  | Metal Gear     | { sku: 109127072, ean: 512312342 } |  | 3  | Final Fantasy  | { ean: 109127072, upc: 999284928 } |  

Nested attributes with tabs (has_many)

Posted: 23 May 2016 06:24 AM PDT

I'm working with tabs lately, and after some experiments, I've decided to adapt one tab to show one or more instancies of one model (Contact). Well, following the steps of fields_for, created some tab-pane, under tab-content that's under the principal. The logic is :

Dados Básicos | Endereço | Contatos

(Contact 1)(Contact 2)(Contact 3)...

After the nav-pills, should be showing the respective Contact, but it show nothing. Is there any problem in routing? (With the #contact-... etc)

<div class="inner">   <ul class="nav nav-tabs">    <li class="active"><a href="#dados" data-toggle="tab">Dados Básicos</a>  </li>    <li><a href="#adresses" data-toggle="tab">Endereço</a></li>    <li><a href="#contacts" data-toggle="tab">Contatos</a></li>  </ul>  ...  <div class="tab-content">   <div class="tab-pane" id="contacts">  <ul class="nav nav-pills">    <% @customer.contacts.each_with_index do |co, i| %>      <% if i==0 %><li class="active"><% else %><li><% end %>      <a href="#contact-<%= i %>"><%= co.nome %></a></li>    <% end %>  </ul>    <div class="tab-content">    <%= f.fields_for :contacts do |k| %>      <div class="tab-pane" id="contact-<%= k.index %>">        <div class="well">             <%= k.hidden_field :id %>            <%= k.label :nome, "Nome" %>          <%= k.text_field :nome, class: 'form-control' %>            <%= k.label :setor, "Setor" %>          <%= k.text_field :setor, class: 'form-control' %>            <%= k.label :email, "Email" %>          <%= k.email_field :email, class: 'form-control' %>            <%= k.label :observacao, "Observação" %>          <%= k.text_area :observacao, class: 'form-control' %>            <%= k.fields_for :telephones do |tel| %>            <%= tel.hidden_field :id %>            <%= tel.label :telefone, "Telefone" %>            <%= tel.text_field :telefone, class: 'form-control' %>          <% end %>        </div>        <%= f.submit "Salvar Alterações", class: "btn btn-primary" %>      </div>    <% end %>  </div>  ...  

How to see rabbitmq server logs on heroku?

Posted: 23 May 2016 06:21 AM PDT

What is the command to see rabbitmq server logs on heroku, either from GUI or from CLI?

Thanks!

Rails console can't connect to database but rake tasks can

Posted: 23 May 2016 06:44 AM PDT

I have a rails app that is using the one click DO image.

I can run any of the rake db:* successfully but when I run rails console I can't connect to the db.

How can I fix it? The app is working fine. So I think is a rails console problem.

Console output:

deployer:/home/rails$ RAILS_ENV=production bundle exec rake db:migrate    ActiveRecord::SchemaMigration Load (3.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"    deployer:/home/rails$ echo $APP_DATABASE_PASSWORD  [redacted database password]    deployer:/home/rails$ RAILS_ENV=production bundle exec rails console  Running via Spring preloader in process 25038  Loading production environment (Rails 4.2.6)  2.3.0 :001 > User.connection  PG::ConnectionBad: fe_sendauth: no password supplied  

database.yml

default: &default    adapter: postgresql    encoding: unicode    pool: 5    host: localhost    username: rails    password: <%= ENV['APP_DATABASE_PASSWORD'] %>    production:    <<: *default    database: production    username: rails    password: <%= ENV['APP_DATABASE_PASSWORD'] %>  

EDIT

Looking around I found that ActiveRecord::Base.configurations has password: nil. Why then the server process reads the password but console doesn't?

I added ActiveRecord::Base.configurations to an initializer. At initialization the password is present.

On console ActiveRecord::Base.configurations returns all the info as expected, except by the password. I even have reload the default vars with . /etc/defaults/unicorn

EDIT 2

ActiveRecord::Base.configurations on RAILS_ENV=production bundle exec rails console

{"default"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil},   "development"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"development"},   "test"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"test"},   "production"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"production"}}  

ActiveRecord::Base.configurations on APP_DATABASE_PASSWORD=password RAILS_ENV=production bundle exec rails console

{"default"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil},   "development"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"development"},   "test"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"test"},   "production"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>nil,     "database"=>"production"}}  

ActiveRecord::Base.configurations on RAILS_ENV=production bundle exec rails server

{"default"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>[password]},   "development"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>[password],     "database"=>"development"},   "test"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>[password],     "database"=>"test"},   "production"=>    {"adapter"=>"postgresql",     "encoding"=>"unicode",     "pool"=>5,     "host"=>"localhost",     "username"=>"rails",     "password"=>[password],     "database"=>"production"}}  

Rails query related to polymorphic association

Posted: 23 May 2016 06:21 AM PDT

I'm trying to find a query through which I can pull the records from the database... Below is the example

class Apple < AR::Base    has_many :bananas    has_many :events, as: :eventable  end    class Banana < AR::Base    belongs_to :apple    has_many :events, as: :eventable  end    class Event < AR::Base    belongs_to :eventable, polymorphic: true  end  

Can I write any single query, where I can pull all the events of a specific apple and all the events of the bananas related to that specific apple.

How to write the below SQL query in rails 3 ActiveRecord?

Posted: 23 May 2016 05:50 AM PDT

select * from  (  SELECT DISTINCT ON (table1.id) table1.*, table3.date_filed as date_filed  FROM          table1 LEFT JOIN table2 ON table2.id = table1.some_id          INNER JOIN table3 ON table2.id = table3.some_id  WHERE      (          status IN('Supervisor Accepted')      )      AND(table3.is_main)  )first_result  ORDER BY date_filed ASC LIMIT 25 OFFSET 0  

Is there any way to run main/subset query in the database side through Active::record (Rails 3). I don't want run the first_result(First db query) and the order by on the top of the result(Second db query).

I tried the below:

    # First query run         first_result = Table1.select('DISTINCT ON (table1.id) table1.*, table3.date_filed').      joins('LEFT JOIN table2 ON table2.id = table1.some_id'). # I don't want a association here      joins('INNER JOIN table3 ON table2.id = table3.some_id').      where('table3.is_main')        # Second query run, WHICH is UGLY and not working properly      Table1.where(id: first_result.collect(:&id)).      order_by('date_filed ASC')      page(page).      per_page(per_page)  

In my project controller there is a function "demo" which returns either true or false

Posted: 23 May 2016 05:43 AM PDT

I am using protect_from_forgery in application controller. I want to disable forgery when demo return true. can anyone help me with this ?

Trying to highlight a substring with JavaScript

Posted: 23 May 2016 07:13 AM PDT

I want to write a JS function which will, within an element (a td), find a substring, and highlight it. It only needs to work for the first occurrence of the substring within the element. I am just trying to highlight some keywords on my blog.

Here is what I have tried so far -

JavaScript

function highlight(s, search) {      return s.replace(new RegExp(          search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'      ), '<b>$&</b>');  }  

Note the object['highlight'] is an object I have access to in my Ruby on Rails code.

HTML

<div>    <table>      <thead>        <tr>          <th>...</th>          </tr>             </thead>      <tbody>        <tr>          <td class="test">This element contains text to be highlighted</td>          <script>highlight($('test').html(), <% object['highlight'].first %>)</script>        </tr>      </tbody>    </table>  </div>  

When I try to run this code, nothing is highlighted.

Can anyone see what I have done incorrectly here ?

Thanks

Doorkeeper OAuth2: how to login from sample app with Password Grant flow

Posted: 23 May 2016 06:02 AM PDT

I have an API app with Doorkeeper gem as OAuth2 provider. It has applications and users (username and password) as the models. Another applications can intercat with the API only after authentication. Currently my app provides only client_credentials and password flows.

How can I implement the authenctication form with username and password in sample application that will interact with the API? Thanks

Rails Copying a model with its associations

Posted: 23 May 2016 05:12 AM PDT

This is just a general question about copying a model with its database assoications. What is the proper strategy for copying? what happens if for example an association 3 levels deep fails, do you delete the parents as well?

Updating Rails from 2.3.8 [on hold]

Posted: 23 May 2016 05:00 AM PDT

I recently purchased a non-profit website written in Ruby on Rails. A developer informed me that it is written in version 2.3.8. I have been told it is not a complex app. Can it be updated to current version - I am receiving conflicting advice.

Rails Select Most Popular Products

Posted: 23 May 2016 05:48 AM PDT

I need to get a list of '10 most popular' products. I think that the best way to do this is to use Orders table (model) that has a reference to Products.

I know what I should do but I don't know how to write it. This is how I would do this in a MySQL:

SELECT products.* FROM (SELECT product_id, count(product_id) as count from Orders GROUP BY product_id ORDER BY count DESC LIMIT 10) AS O LEFT OUTER JOIN products ON Products.id = O.product_id

Update:

How I can write the query in Rails?

For example: Order.group(:product_id).count...

activerecord PostgreSQLAdapter override sql_for_insert, query, execute and update_sql

Posted: 23 May 2016 04:35 AM PDT

I want to update all sql statements for the queries generated for sql_for_insert, query, execute and update_sql for postgres. I'm using rails 3.2.17. Main aim is to change the column names to lower case. I tried to define a class "class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter" in initializers, methods are called over there, but I can't call super as my class isn't extended from any other class.

Ruby: Skip element in loop if an exception is raised

Posted: 23 May 2016 06:45 AM PDT

I have the following method:

def fetch_something    @fetch_something ||= array_of_names.inject({}) do |results, name|      begin        results[name] = fetch_value!(name)      rescue NoMethodError, RuntimeError        next      end        results    end  end  

To its purpose: It fetches a value for a given name that can raise an error, in which case it will ignore the name and try the next one.

While this works fine I get an error from Rubocop that says:

Lint/NextWithoutAccumulator: Use next with an accumulator argument in a reduce.

Googling that error leads me to http://www.rubydoc.info/gems/rubocop/0.36.0/RuboCop/Cop/Lint/NextWithoutAccumulator where it says to not omit the accumulator, which would result in a method looking like this:

def fetch_something    @fetch_something ||= array_of_names.inject({}) do |results, name|      begin        results[name] = fetch_value!(name)      rescue NoMethodError, RuntimeError        next(name)      end        results    end  end  

The problem is, that this change breaks the otherwise working method. Any ideas on how to tackle that?

Update: Demonstrational example:
array_of_names = ['name1','name2','name3']    def fetch_value!(name)    # some code that raises an error if the name doesn't correspond to anything  end    fetch_something    # => {'name1' => {key1: 'value1', ...}, 'name3' => {key3: 'value3', ...}}  # 'name2' is missing since it wasn't found durcing the lookup  

rails4 dependent destroy callback error

Posted: 23 May 2016 04:02 AM PDT

I have a role attribute on the ProductUser model. Users can be deleted by the owner (role), and I wanna make sure the owner can't delete himself while the product exists. However, when the product gets deleted all the product_users should be gone including the owner.

The following code throws an ActiveRecord::RecordNotDestroyed - Failed to destroy the record error when I try to delete the product. I guess this is because of the order of the execution due to the dependent: :destroy. How can I make this work?

class ProductUser < ActiveRecord::Base    belongs_to :user    belongs_to :product, touch: true      before_destroy :check_for_owner      def check_for_owner      if product && role == "owner" #If I use simply: if role == "owner", it still doesn't work.        errors[:base] << "Owner can't be deleted!"        return false      end    end  end      class Product < ActiveRecord::Base    has_many :product_users, dependent: :destroy    ....  end  

Bulk insert data into rails DB with associations

Posted: 23 May 2016 05:48 AM PDT

I wanted to copy and bulk insert data to database (using bulk_insert GEM), so I tried the following:

@questionnaires = Questionnaire.where(:id => params[:id])  @new_sections = []    @questionnaires.includes(:sections, :questions).each do |questionnaire|    questionnaire.sections.each do |section|      s = section.dup      s.questionnaire_id = nil      new_section = Section.new( s.attributes.reject{|k, v| ["id", "created_at", "updated_at"].include?(k)} )      questions = []        section.questions.each do |question|        q = question.dup        q.section_id = nil        questions << q.attributes.reject{|k, v| ["id", "created_at", "updated_at"].include?(k)}      end        new_section.questions.build(questions)      @new_sections << new_section    end  end  

Now, here @new_sections has all the sections with associated questions, but is not saved.

SAVING

Section.transaction do    Section.bulk_insert values: @new_sections.map(&:attributes)  end  

But, this only saves the sections but not it's associations. How can I save associations(questions) as well.

EDIT

Now, I came across this https://github.com/zdennis/activerecord-import/wiki GEM and I'm trying the Multi-Level Example, still questions are not saved. Any ideas?

Where should I save values that are commonly used in a Rails model

Posted: 23 May 2016 03:43 AM PDT

Assuming that there is a Person model that have a column point and point_standard_score.

To get standard score, I need to calculate standard deviation by using point column. It takes some time to calculate it, so I want to save it like in database.

But I don't know where should I save the value that is used commonly from all instance of the model.

I found that we should avoid to use class variable in rails. Why should we avoid using class variables @@ in rails?

Where and how should I save the value?

Database migrations to heroku don't work

Posted: 23 May 2016 03:41 AM PDT

I've been trying to migrate my database to heroku, without success. I have added a few more users to my database and when trying to log them in with email address and password on my heroku app, I get invalid email/password error, even though this works perfectly fine on my local server. NO errors at all when doing all the steps described below.

As suggested in a previous post, I've tried the following:

  1. Made changes to local code
  2. Ran any migrations LOCALLY - I used bundle exec rake db:migrate
  3. Added all changed files to Git git add -A
  4. Commit all added files to git git commit -m "Adding features"
  5. Pushed the changes to Heroku git push heroku master
  6. Ran heroku run rake db:migrate

After I run this I get:

astelvida:~/workspace/sample_app (master) $ heroku run rake db:migrate  Running rake db:migrate on ⬢ shrouded-ravine-80000... up, run.2794   ActiveRecord::SchemaMigration Load (0.8ms)    SELECT "schema_migrations".* FROM "schema_migrations"  
  1. Following migrations do heroku restart

I've also checked my .sqlite3 file to check that the new users actually exist in the database.

I've also tried this: $ bundle exec rake db:migrate RAILS_ENV=production

I've also updated my gemfile.lock.

My gems in dev & production:

group :development, :test do    gem 'sqlite3',     '1.3.9'    gem 'byebug',      '3.4.0'    gem 'web-console', '2.0.0.beta3'    gem 'spring',      '1.1.3'  end    group :production do    gem 'pg',             '0.17.1'    gem 'rails_12factor', '0.0.2'    gem 'puma',           '3.1.0'  end  

Note: I run bundle install --without production, however this is how I've always been using it, and the login data works for some of the users i've created in the past. Also I'm using rails 4.2.2.

Cancancan block not working

Posted: 23 May 2016 03:53 AM PDT

I'm currently using Cancancan for my authorization. I have models User, Company, and Asset with the following associations.

#User  has_many :user_companies  has_many :companies, through: :user_companies    #Comapny  has_many :user_companies  has_many :users, through: :user_companies  has_many :assets    #Asset  belongs_to :company  

As you can see, assets is deeply nested with a many-to-many association in its ancestry. To make sure a User can only view, index, etc etc the Assets of a Company to whom he as access, I have configured my abilities as follows:

def initialize(user)      user ||=User.new #guest user        can :do_this, :on_this      if user.role=="god"            can :manage, :all        elsif user.role=='user' and user.id          can :manage, Asset do |asset|              asset.company.user_companies.where(user: user).exists?          end      end  end  

However, as it stands any user can go into any company's Asset index without a problem. If of course, if I delete this block no user (except 'god') can navigate there (as would be expected).

What might I be missing?

Thanks in advance!

JS format in the controller

Posted: 23 May 2016 03:20 AM PDT

Let's assume I have a controller action that whenever you try to access it via a js format, I want to render nothing.

def no_js_please    # there isn't a no_js_please partial or view    respond_to do |format|      format.html { # render a template }      format.json { render json: {valid: true} }      format.js { render nothing: true, status: :not_found }    end  end  

When you access the endpoint via html or JSON, it works just fine. When you try to access it via JS it doesn't work. However, it does actually execute the block, because if I add a binding.pry within the js block, it gets picked up.

However, this does work:

def no_js_please    if request.format.js?      render nothing: true, status: :not_found    end  end  

So what's the difference between the two?

EDIT

As a human mentioned below, what's the actual error? So, in this particular case, it raises a ActionController::InvalidCrossOriginRequest.

How can I print data using the puts statement to development.log file in rails?

Posted: 23 May 2016 05:26 AM PDT

When I write Print statements those are not getting printed in the log/development.log file when I'm working in development mode. How can I make puts statement work in development.log file in rails?

How to check all filtered records in Activeadmin?

Posted: 23 May 2016 03:38 AM PDT

I've filtered some user's records by criteria. Now I want to send an email for all of them, not only for users that are on first page. How to check all filtered users? Something like:

collection_action :check_filtered do |items|      items = collection      items.check_filtered  end  

No comments:

Post a Comment