Friday, December 30, 2016

How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord? | Fixed issues

How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord? | Fixed issues


How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord?

Posted: 30 Dec 2016 07:25 AM PST

My team's project is a Rails 4.2 app using Mongoid 4. A new feature we are adding requires us to read data from a Postgres DB and use those records in the app through an intermediary object. In other words, our app will play with ActiveModel objects (non-persisted) that contain a mix of data from Mongoid models and ActiveRecord models, and thus can do all the normal cool Rails stuff with Controllers and Views, etc. (We think it's clever.) The intention right now is that we will never write to the SQL tables, just read. Any new data stored will be in mongodb.

For my development environment, the first steps seemed pretty straight-forward:

  • I added pg to the gemfile
  • I added require "active_record/railtie" to application.rb
  • I made my new models in the normal ActiveRecord way (although since I was working with an existing database, I changed the class names to something more meaningful and set the table names accordingly)
  • I added a database.yml file (we didn't need one with mongoid) with all the correct postgres info
  • I created the schema.rb file using rake db:schema:dump. That took a while to figure out I needed it, but I got there.

Using the rails console, I was able to prove to myself that I could search/find objects in both databases. So far so good.

When I first fired up the rspec tests, there were tons of failures related to validation errors because "records already existed with that name". Long investigation story short, I fixed by setting all DatabaseCleaner calls to be DatabaseCleaner[:mongoid], and that got rspec passing again. (I still have no idea what was actually happening behind the scenes.)

BUT, Cucumber (feature) tests? I can't even get them started. It keeps saying:

Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=test  

No! All those migrations we have are for MONGO. There are no SQL/ActiveRecord migrations. Not surprisingly, that rake fails:

rake aborted! ArgumentError: wrong number of arguments (2 for 0).  

I tried this series of commands:

rake db:drop RAILS_ENV=test  rake db:create RAILS_ENV=test  rake db:schema:load RAILS_ENV=test  

but cucumber still gives the same migration pending error.

So I'm stuck! I haven't found anyone doing what we're trying to do. I know there HAS to be someone, I just haven't found the right search terms, apparently.

The worst part of all this is I had no intention of even using an ActiveRecord test database at all, I was simply going to mock those records in my tests. How can I tell the app, "I only need ActiveRecord for runtime, not testing. Stop looking at the migrations, ActiveRecord, those aren't for you!"

I have run out of ideas and words to search with. I've been trying to solve this problem for a couple of days now and have tried SO many different things, please forgive me if I've left some of those out here. Any assistance would be greatly appreciated.

Unexplicable InvalidURIError after controller testing

Posted: 30 Dec 2016 07:03 AM PST

I was testing my Rails 5.0 application with the following code:

  test "destroy should require logged-in user" do      assert_no_difference 'AtpSelection.count' do        delete :destroy, params: { id: atp_selections(:selection_1) }      end      assert_redirected_to login_url    end  

but the test kept failing:

ERROR["test_destroy_should_require_logged-in_user", AtpSelectionsControllerTest, 1.9559332270000596]   test_destroy_should_require_logged-in_user#AtpSelectionsControllerTest (1.96s)  URI::InvalidURIError:         URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80destroy  

So, in order for the test to pass, I had to change my code using instead the following code:

  test "destroy should require logged-in user" do      assert_no_difference 'AtpSelection.count' do        delete atp_selection_path(atp_selections(:selection_1))      end      assert_redirected_to login_url    end  

I have no idea why I could not make the test pass calling delete directly on the controller action :destroy. I made this same choice in other tests I created before for other controllers and they succeed without raising errors.

What i wrong with my html.erb file?

Posted: 30 Dec 2016 07:08 AM PST

from the code below, I get the following error:

/home/ubuntu/workspace/portfolio/app/views/projects/_project_form.html.erb:36: syntax error, unexpected keyword_ensure, expecting end-of-input

because it is a syntax error, I am guessing I wont need to provide other details but if you guys need me to post more feel free to ask.

    <%= form_for @project do |f| %>    <% if @project.errors.any? %>      <div id="error_explanation">        <h2>          <%= "#{pluralize(@project.errors.count, "error")} prohibited this project from being saved:" %>        </h2>        <ul>          <% @project.errors.full_messages.each do |msg| %>            <li>              <%= msg %>            </li>          <% end %>        </ul>      </div>    <% end %>    <div class="field">      <%= f.label :client %>        <p>          <%= @project.client.name %>        </p>        <%= f.hidden_field:note_id, value: @project.client.id  %>      <% end %>    </div>    <div class="field">      <%= f.label :project_description %>      <%= f.text_area :project_description %>    </div>    <div class="field">      <%= f.label :project_timescale %>      <%= f.text_field :project_timescale %>    </div>    <div class="actions">      <%= f.submit 'Save' %>    </div>    <% end %>  

Database configuration errors while deploying Rails app to Heroku

Posted: 30 Dec 2016 06:55 AM PST

I'm using Rails 4.2.3

I received the classic "sqlite not supported" error initially, and then removed all references to sqlite.

Now I'm getting:

remote:        Cleaning up the bundler cache.  remote: -----> Detecting rake tasks  remote: -----> Preparing app for Rails asset pipeline  remote:        Running: rake assets:precompile  remote:        rake aborted!  remote:        URI::InvalidURIError: bad URI(is not URI?): ://user:pass@127.0.0.1/dbname  

My database.yml looks like this:

production:    url: <%= ENV['CLEARDB_DATABASE_URL'] %>  

I've also tried:

production:    url: <%= ENV['DATABASE_URL'] %>    production:    encoding: utf8    pool: 15  

How can i call model method in Rails 5 with ajax?

Posted: 30 Dec 2016 06:53 AM PST

I've a Task model in Rails with this method

    def notify(user)      Task.where(assignee: user).where(notified: false).count  end  

that returns the number of particular tasks. I need to call it via Ajax, how can i do it? I know that i could use it in a controller method and call Ajax to controller (i know how to do this) but then the controller method would be attainable via url.

When is touch_record (belongs_to.rb) called?

Posted: 30 Dec 2016 07:38 AM PST

In this method from belongs_to.rb, def self.touch_record(o, foreign_key, name, touch) I am trying to get the 'o' class.

I try :

bundle show activerecord then open 'thepathgivenbymyfirstcommand' and put a 'binding.pry' in the method

Finally, I moved into a rails project (with belongs_to association already created) and try to update/destroy as they said here :":touch If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute."

but nothing happened, I never stop at the "binding.pry" to get the 'o' variable class.

Do you have any advice ?

Sass::Engine.new Rails | Compiled css file has code from the scss.erb template file causing the css file to have errors

Posted: 30 Dec 2016 06:31 AM PST

I have made use of the Sass engine in rails to produce a custom css file for each element a user can add to the site.

This is my generate css code

def generate_css       Sass::Engine.new(asset_source, {            syntax: :scss,            cache: false,            read_cache: false,            style: :compressed         }).render  end  

The template file it uses is just a list of variables and a sass if statement to check which mix-in to use. This when compiled seems to keep around 22 lines of code from the template file.

This isn't a major problem as the css file still renders in the browser fine but it is annoying knowing I have incorrect/ erroneous files.

Any ideas on how to trim/remove reformat the final compiled css?

How to make this link to send PUT request.?

Posted: 30 Dec 2016 06:33 AM PST

This is a helper method to generate a link in the_comments gem. I want to make it put request.

def approved_comment    "<p class='reply'><a href='/comments/#{@comment.id}/approve_comment'>#{ t('the_comments.approve') }</a>"   end  

If any one know how to make it PUT request please help me.

Using Cassandra in Rails App

Posted: 30 Dec 2016 05:42 AM PST

I have a couple of questions about working with Ruby on Rails and Cassandra. I have a PostgreSQL database and a Cassandra database separate from my Rails application. I would like to access Cassandra to make some queries through my Rails application.

What is the recommended way of Cassandra integration into a Rails app ?

Is there any reference implementation?

Regards,

Rails factory_girls and validation issue

Posted: 30 Dec 2016 06:07 AM PST

I have HABTM association

my models

 class Ssr < ActiveRecord::Base      has_and_belongs_to_many :ssr_groups      validates :ssr_groups, presence: true   end    class SsrGroup < ActiveRecord::Base    has_and_belongs_to_many :ssrs, dependent: :destroy    validates :name, presence: true  end  

my factories

  FactoryGirl.define do    factory :ssr do      type 'type'       ssr_groups     end   end    FactoryGirl.define do    factory :ssr_group, class: 'SsrGroup', aliases: [:ssr_groups] do      name { SecureRandom.hex }    end  end  

My problem is when i want to create FactoryGirl.create(:ssr)

i have got NoMethodError: undefined method each for #<SsrGroup:0x007fbfdf792100>

Why it happens?

/Users/user/.rvm/rubies/default/bin/ruby: No such file or directory -- script/rails (LoadError)

Posted: 30 Dec 2016 05:32 AM PST

I want to use Ruby with Netbeans IDE. But I get error when I start Ruby on Rails project in console:

/Users/user/.rvm/rubies/default/bin/ruby: No such file or directory -- script/rails (LoadError)  

But there is a file:

file /Users/user/.rvm/rubies/default/bin/ruby  /Users/user/.rvm/rubies/default/bin/ruby: Mach-O 64-bit executable x86_64  

Do you know how I can solve this issue?

Production error env

Posted: 30 Dec 2016 06:57 AM PST

In development mode the rails normally run, but not in production. I already ran rake db: migrate

file production.log

[1m[36mActiveRecord::SchemaMigration Load (0.9ms)[0m  [1mSELECT "schema_migrations".* FROM "schema_migrations"  

Rails navbar conditional and getting No route matches in root_path

Posted: 30 Dec 2016 05:46 AM PST

Hello I want to show the search form inside the navbar only in the index page of products and the show page of the product. The thing is that it is showing on both the index page and the show page but when I click home to go to the root_path I get the following error:

No route matches {:action=>"show", :controller=>"products"} missing required keys: [:id]

How can I avoid that? This is my code in the application.html.erb:

<% if current_page?(products_path) || (product_path) %>        <div class="col-sm-3 col-md-3 pull-right">          <form class="navbar-form" role="search">          <div class="input-group">              <input type="text" class="form-control" placeholder="Search" name="search_term" id="search_term">              <div class="input-group-btn">                  <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>              </div>          </div>          </form>          </div>      <% end %>

Rails: how to check CSS or JS code code from a string?

Posted: 30 Dec 2016 05:34 AM PST

In a code string I have stored a piece of code, can be CSS, SASS, SCSS, JavaScript or CoffeeScript.

I need to check if the syntax is correct. Currently I found a ugly hack which works. Do you know a better solution?

def check_js    if language == 'coffee'      CoffeeScript.compile code    else      Uglifier.compile code    end  rescue ExecJS::RuntimeError => e    errors.add :code, e.message  end    def check_css    if language == 'css'      Sass::CSS.new(code).render    else      Sass.compile code, syntax: language.to_sym    end  rescue Sass::SyntaxError => e    errors.add :code, e.message  end  

FriendlyID for child

Posted: 30 Dec 2016 05:32 AM PST

I have a Project model that belongs to a User. A User has_many Projects. I have setup FriendlyID according to the gem instructions for User model, however it is not working in this scenario.

<%= link_to gravatar_for(project.user, size: 50), project.user %>  

The above creates a link with the numerical ID of the user (project.user) instead of a friendly URL (i.e. http://localhost:3000/users/102 instead of what I want, http://localhost:3000/users/*random-gen-string*).

User.rb file:

class User < ApplicationRecord    extend FriendlyId    friendly_id :generated_slug, use: :slugged      def generated_slug      require 'securerandom'      @random_slug ||= persisted? ? friendly_id : SecureRandom.hex(15)    end  

I think the problem is that project.user is set in the projects_controller.rb to the user ID (via current_user.projects.build...). If I could somehow access the Friendly ID for User in the projects_controller.rb I may be able to save it in the database and access it like project.user_friendly_id. Not sure..

Relevant code in projects_controller:

def create   @project = current_user.projects.build(project_params)   # code  end  

What is the best way to go about making the above link link to the Friendly ID and not the user (i.e. http://localhost:3000/users/*random-gen-string* is what I want instead of http://localhost:3000/users/102)?

getting error, Mysql2::Error: You have an error in your SQL syntax in rails?

Posted: 30 Dec 2016 04:44 AM PST

What needs to be changed in the below queries?. i want all those employees whose date_of_leaving is null or the date_of_leaving is in between the past 60 days or the date_of_leaving is greater than or equal to the Date.today or current date.

employees = @company.employees.where('date_of_leaving BETWEEN ? AND ? OR date_of_leaving IS NULL OR date_of_leaving IS >= Date.today', Date.today - 60, Date.today)  

i tried in another way also like below.

employees = Company.find(4).employees.where('date_of_leaving BETWEEN ? AND ? OR date_of_leaving IS NULL OR date_of_leaving IS >= ?', Date.today - 60, Date.today,Date.today)  

Rails, how to use a block in where statement

Posted: 30 Dec 2016 06:33 AM PST

Taken from this stackoverflow-question, one can use a block for a query, like this:

Consumer.find do |c|    c.id == 3  end  

I want to do the same with a "where" query, for example:

mainCustomers = Customer.where do |c|   c.id == c.main  end  

When I do this, I get something like this:

=> #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560 @scope=#<ActiveRecord::Relation   

I can't use ActiveRecord methods, for example:

irb(main):013:0> mainCustomers.last  NoMethodError: undefined method `last' for #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560>  

or

irb(main):014:0> mainCustomers.count  NoMethodError: undefined method `count' for #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560>  

What is the correct way for using blocks in a where statement?

Adding a scope to ruby gem validation of uniqueness

Posted: 30 Dec 2016 04:32 AM PST

acts-as-taggable-on gem has a built-in uniqueness validation:

validates_uniqueness_of :name, if: :validates_name_uniqueness?    def validates_name_uniqueness?    true  end  

How do I add a scope to this validation?

I want to add scope: :user_id and don't know how to edit a gem source code.

Two levels of nested attributes and strong parameters

Posted: 30 Dec 2016 03:21 AM PST

I've ported a Rails app from Rails 3 to Rails 4 and most things work now, except for a problem with two levels of nested attributes:

  • I have ProductGroups, Variants and Prices.
  • Each ProductGroup has one or more variants. One of them is the master variant.
  • Each variant has many prices (one for each region).

I have a controller that updates ProductGroups. When the ProductGroup is updated, the master variant is updated at the same time. And prices in the master variant are also updated.

Here's a test that describes what's expected to happend:

test "should update master variant" do      login_as accounts(:johnny_admin)        p = ProductGroup.find product_groups(:toothbrush).id      assert_equal "10123", p.artno      assert_equal "10123", p.master_variant.artno        puts(p.master_variant.prices.to_a.to_s)        post :update,           id: product_groups(:toothbrush),           p: 'setup',           product_group: {             master_variant_attributes: {               artno: "20222",               supplier_artno: "1010",               prices_attributes: { "0": { price: "55", id: prices(:toothbrush_price_se).id } }             }           }      assert_response :redirect    assert_redirected_to edit_admin_product_group_path(p, :p => 'setup')      p = ProductGroup.find product_groups(:toothbrush).id    assert_equal "20222", p.artno    assert_equal "20222", p.master_variant.artno    assert_equal "1010", p.master_variant.supplier_artno      price = Prices.find prices(:toothbrush_price_se).id    assert_equal 55, price.price  end  

But it fails with this error:

# Running:    .......[#<Price id: 510149407, variant_id: 630858089, region_id: 102782309, price: #<BigDecimal:55d2732f50a8,'0.95E2',9(18)>, created_at: "2016-12-30 11:14:28", updated_at: "2016-12-30 11:14:28">, #<Price id: 524805804, variant_id: 630858089, region_id: 960235695, price: #<BigDecimal:55d27339c510,'0.1E2',9(18)>, created_at: "2016-12-30 11:14:28", updated_at: "2016-12-30 11:14:28">]  E    Finished in 1.279989s, 6.2501 runs/s, 20.3127 assertions/s.      1) Error:  Admin::ProductGroupsControllerTest#test_should_update_master_variant:  ActiveRecord::RecordNotFound: Couldn't find Price with ID=510149407 for Variant with ID=      app/controllers/admin/product_groups_controller.rb:150:in `update'      test/functional/admin/product_groups_controller_test.rb:103:in `block in <class:ProductGroupsControllerTest>'  

As you can see in the debug output, there is a price with ID 510149407 for that variant. And why is the ID of the variant empty?

I'm totally stuck.

Here's the permits for ProductGroup that I'm using:

  def product_group_params      prices_attributes = { :prices_attributes => [ :id, :price ] }      master_variant_attributes = { :master_variant_attributes => [        :unit, :vat, :artno, :width, :height, :depth,        :description, :in_stock, :in_stock_verified_at,        :status, :supplier_id, :supplier_artno,        :alt_supplier_id, :alt_supplier_artno,        :supplier_price, :alt_supplier_price,        :supplier_reduction, :alt_supplier_reduction,        :supplier_carriage_percentage, :alt_supplier_carriage_percentage,        :our_expenses, :percentage_markup, :taric_code_id,        :reduction_group_id, :vendor_id, :vendor_artno, :is_expired,        :show_price, :reorder_point,        :place_of_storage_a, :place_of_storage_b, :place_of_storage_c,        prices_attributes      ] }        params.require(:product_group).permit(:updated_by,                                            :title, :description, :license_code, :fixme,                                            master_variant_attributes,                                            :notes, :vat, :artno, :unit,                                            :width, :height, :depth, :in_stock, :published, :reorder_point,                                            :current_version, :changelog, :price_by_start_cost_and_per_unit,                                            :start_cost_variant_id, :unit_cost_variant_id,                                            :category_ids => [])    end  

Here's how ProductGroup relates to the master variant:

  has_one :master_variant,            -> { where(is_master: true, deleted_at: nil) },            :class_name => "Variant",            :foreign_key => 'product_group_id',            :dependent => :destroy,            :autosave => true    accepts_nested_attributes_for :master_variant  

Here's how Variant relates to Prices:

  has_many :prices, -> { order('region_id') }, :dependent => :destroy    accepts_nested_attributes_for :prices  

I will gladly post any other excerpts from the code if it is of any help, but I'm not sure what could be of interest right now.

Any hints would be much appreciated!

Error: Postgres database import in docker container

Posted: 30 Dec 2016 05:49 AM PST

I'm running a ruby on rails application in docker container. I want to create and then restore the database dump in postgres container. But I'm

Below is what I've done so far:

1) Added bash script in /docker-entrypoint-initdb.d folder. Script is just to create database:

psql -U docker -d postgres -c 'create database dbname;'

RESULT: Database created but rails server exited with code 0. Error: web_1 exited with code 0

2) Added script to be executed before docker-compose up.

# Run docker db container  echo "Running db container"  docker-compose run -d db    # Sleep for 10 sec so that container have time to run  echo "Sleep for 10 sec"  sleep 10    echo 'Copying db_dump.gz to db container'  docker cp db_dump/db_dump.gz $(docker-compose ps -q db):/    # Create database `dbname`  echo 'Creating database `dbname`'  docker exec -i $(docker-compose ps -q db) psql -U docker -d postgres -c 'create database dbname;'    echo 'importing database `dbname`'  docker exec -i $(docker-compose ps -q db) bash -c "gunzip -c /db_dump.gz | psql -U postgres dbname"  

RESULT: Database created and restored data. But another container runs while running web application server using docker-compose up.

docker--compose.yml:

version: '2'    services:      db:      image: postgres        environment:        - POSTGRES_PASSWORD=docker        - POSTGRES_USER=docker      web:      build: .      command: bundle exec rails s -p 3000 -b '0.0.0.0' -d      image: uname/application      links:        - db      ports:        - "3000:3000"      depends_on:        - db      tty: true  

Can some one please help to create and import database?

EDIT:

I've tried one more approach by adding POSTGRES_DB=db_name environment variable in docker-compose.yml file so that database will be created and after running the application (docker-compose up), I'll import the database. But getting an error: web_1 exited with code 0.

I'm confused why I'm getting this error (in first and third approach), seems to be something is messed up in docker-compose file.

How to password protect Munin directory?

Posted: 30 Dec 2016 03:19 AM PST

I followed Munin, apache and how to password protect munin and have added .htaccess file in /var/www/munin with this code

AuthType Basic  AuthName "My Protected Area"  AuthUserFile /var/www/munin/.htpasswd  Require valid-user  

I have also generated .htpasswd file with apache utils has it has the username and md5 password. Now after reloading and restarting apache, I can still see example.com/munin content.

I am running rails on example.com but I don't think that has anything to do with munin which resides on different path. Can you suggest me what I am missing out or if there is any other way using which I can password protect munin content ?

How obtain connect with OAuth 2 using Postman?

Posted: 30 Dec 2016 03:22 AM PST

My API uses the devise_token_auth (omniauth) gem for authentication in the Rails 5 backend. The frontend are using ng-token-auth (Angular 1.x).

I have all the API requests in Postman. I did the security implementation and I need authenticate Postman with every request. Devise_token_auth uses authentication with OAuth 2 and I am having difficulty to implementing this authentication.

enter image description here

For this type of authentication, using Postman, what is the process needed to obtain the connection?

How to merge multiple docx files into one docx file in rails?

Posted: 30 Dec 2016 03:09 AM PST

I have multiple docx files with same header and footer and want to merge them together to form one document keeping the header and footer intact.

Create Wistia model in Ruby on Rails

Posted: 30 Dec 2016 03:40 AM PST

I am building currently an web app where the admin will be able to post a title with a description and a link / embedded form of Wistia Video Player.

Currently my setup is:

  • Welcome Page
  • Dashboard Page with Dashboard Controller (here only the admin will be able to post, edit things, all other users can only watch/comment)

How do i create a model for this? Normally i would create a model like this:

rails g model Video title:string description:text   

But how do i implement the Wistia Video Player, so that everytime the Admin creates a new post, he will be able to link/embedded a new video?

Rails: Accessing image files after being uploaded

Posted: 30 Dec 2016 02:56 AM PST

I am writing a Ruby on Rails 5 app. I just learned how to upload an image without using paperclip,carrierwave, or refile. I have used refile in the past but for this app, I wanted to learn how to do it with out those third party gems. And it was not that difficult to do. I have successfully uploaded a file. My problem is accessing the image afterwards! I thought this would be rather simple. But NO!

I have image files being uploaded to "/public/images/page/image.jpg"

I have added "/public/images/page" to the assets path in app/initializers/assets.rb

I have tried straight img tag like this:

<img class="pic left" src="/public/images/page/mars01.jpg" alt="Mars01" />  

I get a "(No route matches [GET] "/public/images/page/mars01.jpg")" error. I have tried:

<%= image_tag "/public/images/page/#{@page.image}", class: 'pic left' %>  

basically the same as tag, get same results. Also tried:

<img class="pic left" src='<%= image_path "#{@page.image}" %>' />  

still get routing error, but only looking in "/images" directory. I am still in development mode, so I thought that image_path would be the correct path.

What is the correct way of accessing an image, that was just uploaded to a directory outside of the asset pipeline? That will work in development or production env? I really thought this would be straight forward.

Rails 4 after_commit nested conditions issue

Posted: 30 Dec 2016 04:34 AM PST

I would like to trigger the same function for after_commit on both update and create BUT I would like to apply a particular condition only for update.

For now, my only solution was to duplicate the function and make two different after_commit like this:

after_commit :my_method_on_update,                 on: :update,                 if: ->(foo) { foo.previous_changes.key?(:bar) }    after_commit :my_method_on_destroy, on: :destroy    def my_method_on_update    # stuff  end    def my_method_on_destroy    # same stuff here  end  

Of course it works but it doesn't make the code DRY at all. I'm sure there is a better solution but I haven't found any relevant examples on the official rails doc

What I'd like is something like this:

after_commit :my_method,                 on: :update,                 if: ->(foo) { foo.previous_changes.key?(:bar) },                 on: destroy    def my_method    # stuff  end  

But there is an error with twice the declaration of on.

Active Admin Installation Error

Posted: 30 Dec 2016 04:41 AM PST

I created a sample application in RubyonRails and tried to use Active Admin gem.

Added the below lines to Gem file:

gem 'activeadmin'  gem 'sass-rails'  gem "meta_search", '>= 1.1.0.pre'  

Then ran the following command rails generate active_admin:install but got the below error:

Running via Spring preloader in process 1726  Expected string default value for '--jbuilder'; got true (boolean)  Expected string default value for '--helper'; got true (boolean)  Expected string default value for '--assets'; got true (boolean)  Could not find generator 'active_admin:install'. Maybe you meant 'active_record:model', 'active_record:migration' or 'integration_test'  Run `rails generate --help` for more options.  

what configuration do i need for actionmailer to work in cloud9?

Posted: 30 Dec 2016 02:25 AM PST

I have been following this simple tutorial for sending mail using ActionMailer.

http://guides.rubyonrails.org/action_mailer_basics.html

The configuration i am using in development.rb file is as follows:

  config.action_mailer.delivery_method = :smtp          config.action_mailer.smtp_settings = {            :address => 'smtp.mailgun.org',        :domain => 'sandbox1b1a6a9b09cb4df4b1e7489ad0747f6d.mailgun.org',        :port => 587,        :user_name => 'postmaster@sandbox1b1a6a9b09cb4df4b1e7489ad0747f6d.mailgun.org',        :password => 'validpassword',        :authentication => 'plain'            }        config.action_mailer.raise_delivery_errors = true        config.action_mailer.perform_deliveries = true  

I have also tested with gmail smtp but with no success. The above configuration is for mailgun smtp.

I send email through the terminal and the following message is printed in console. But the email is never received by the recipient. I am doubtful whether i have missed an important configuration for cloud 9 that is not letting me send emails. I appreciate any help! Thanks!

ExampleMailer#sample_email: processed outbound mail in 281.6ms  Sent mail to validemail@gmail.com (30015.9ms)  Date: Fri, 30 Dec 2016 10:20:48 +0000  From: fromemail@gmail.com  To: validemail@gmail.com  Message-ID: <58663500a6530_e5adab0d8803a3@kofhearts-rubyonrails-3267120.mail>  Subject: Sample Email  Mime-Version: 1.0  Content-Type: multipart/alternative;   boundary="--==_mimepart_58663500a41fe_e5adab0d8802e9";   charset=UTF-8  Content-Transfer-Encoding: 7bit      ----==_mimepart_58663500a41fe_e5adab0d8802e9  Content-Type: text/plain;   charset=UTF-8  Content-Transfer-Encoding: 7bit    Hi hello  Sample mail sent using smtp.    ----==_mimepart_58663500a41fe_e5adab0d8802e9  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: 7bit    <!DOCTYPE html>  <html>    <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />      <style>        /* Email styles need to be inline */      </style>    </head>      <body>      <!DOCTYPE html>  <html>    <head>      <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />    </head>    <body>      <h1>Hi dog</h1>      <p>        Sample mail sent using smtp.      </p>    </body>  </html>    </body>  </html>    ----==_mimepart_58663500a41fe_e5adab0d8802e9--  

How to use "has_many through" model in form of active admin

Posted: 30 Dec 2016 02:02 AM PST

So i have model "ClientHotel", "ConferenceRoom", "Slot" and associations between these is like

class Slot < ActiveRecord::Base   belongs_to :conference_room   belongs_to :client_hotel   has_many :bookings  end    class ConferenceRoom < ActiveRecord::Base    belongs_to :client_hotel    has_many :slots    accepts_nested_attributes_for :slots, allow_destroy: true  end    class ClientHotel < ActiveRecord::Base      has_many :slots, through: :conference_rooms    has_many :conference_rooms    has_many :bookings    has_many :holidays    accepts_nested_attributes_for :conference_rooms, allow_destroy: true    accepts_nested_attributes_for :slots, allow_destroy: true  end  

and this is my file in app/admin/client_hotel.rb

ActiveAdmin.register ClientHotel do    permit_params :hotel_name, :email, :password, :password_confirmation     form do |f|     f.inputs do      f.input :hotel_name      f.input :email      f.input :password      f.input :password_confirmation      f.has_many :conference_rooms do |pd|        pd.semantic_errors *pd.object.errors.keys        pd.input :name  

here how to add the slots attributes so that while creating the hotel i should be able to create the conf_room and slot also in one go.

    end    end   f.submit  end    show do    attributes_table do      row :hotel_name      row :email    end  end  end  

suppose i have check-in time & checkout time in slots table so how would i write that in above form

How to save attachment locally using trix editor

Posted: 30 Dec 2016 01:17 AM PST

In ruby on rails, how to save attachment to folder using basecamp's trix html editor

   document.addEventListener("trix-initialize", function(event) {          Trix.Inspector.install(event.target);      });        document.addEventListener("trix-attachment-add", function(event) {          var attachment = event.attachment;          if (attachment.file) {              var xhr = new XMLHttpRequest;              xhr.open("POST", "/img", true);                xhr.upload.onprogress = function(event) {                  var progress = event.loaded / event.total * 100;                  attachment.setUploadProgress(progress);              };                xhr.onload = function() {                  if (xhr.status === 201) {                      setTimeout(function() {                          var url = xhr.responseText;                          attachment.setAttributes({ url: url, href: url });                      }, 30)                  }              };                attachment.setUploadProgress(10);                setTimeout(function() {                  xhr.send(attachment.file);              }, 30)          }      });  

I got this error: POST http://localhost:3000/img 404 (Not Found)

No comments:

Post a Comment