Thursday, September 22, 2016

Digital Ocean Bundle Install Killed | Fixed issues

Digital Ocean Bundle Install Killed | Fixed issues


Digital Ocean Bundle Install Killed

Posted: 22 Sep 2016 08:13 AM PDT

I'm trying to deploy my website on digital ocean following this guide (https://www.digitalocean.com/community/tutorials/how-to-use-the-ruby-on-rails-one-click-application-on-digitalocean) But when I do bundle install I get this message

Fetching gem metadata from https://rubygems.org/.....Killed  

It stops me from continuing the next step. Please help!

Rerun Cucumber step only in case of specific failure

Posted: 22 Sep 2016 08:20 AM PDT

Running Cucumber in CircleCI sometimes the tests fail due to CircleCI's performance. A common failure is a Net::ReadTimeout error, which never seems to happen locally. I want to rescue the steps from that error and try them again, but I do not want to rerun all failed tests.

I could put build a rescue into the specific step(s) that seem to trigger this error, but ideally I would be able to provide Cucumber a list of errors that it rescues once or twice, to rerun that step, before finally letting the error pass through.

Something like:

# support/env.rb  Cucumber.retry_errors = {    # error => number of retries    "Net::ReadTimeoutError" => 2  }  

Does anything like that exist?

Deploy Angular 2 app to Heroku

Posted: 22 Sep 2016 08:10 AM PDT

In the past I always bundled my Angular 1 and Rails apps together and typically used heroku, which has worked great for me. Now that I'm over to Angular 2 I want to separate out my Angular and Rails code. I've created a very basic Angular 2 app via the Angular-Cli, but I haven't been able to figure out how to deploy it to Heroku. I'm not using expressjs or anything like that. Anyone figure it out yet?

Rails - complex model/associations

Posted: 22 Sep 2016 08:09 AM PDT

In my app that I am building to learn rails (RAILS 5), I have following situation I try to get in place. Question is how to do that.

2 models "ANNOTATION" and "DOCUMENT" have a 1-to-many relationship with the model "Tag" (similar to order and order_item); the model "TAG" has a 1-to-1 relationship with the model "TAG_TYPE". One single TAG-record however, can only belong to one ANNOTATION / DOCUMENT and needs to be deleted when the respective ANNOTATION / DOCUMENT gets deleted (I will set dependent: :destroy for that). So, which type of association to use for TAG and TAG_TYPE? Has_one? Has_many? Belongs_to_...?

ANNOTATION.rb and DOCUMENT.rb should have has_many :tags, dependent: :destroy

Now, when adding a TAG to an "ANNOTATION" or "DOCUMENT", the TAG will ge_ extracted text, coordinates and a needs to be assigned to a TAG_TYPE. However, some tag types can only be used once for an annotation / document - depending on the tag_type field "multiple occurrence" is false. How / where do I set this (validation / filter) up in the association?

All suggestions / directions welcome!

Adding Helper Rails Methods to a Directory

Posted: 22 Sep 2016 08:00 AM PDT

I've created a pdfs directory in app/ for invoices and purchase orders (I'm using prawn). Naturally, I want the NumberHelper to be available. Whats the best way to do this?

No such file to load -- 'gem name' using require

Posted: 22 Sep 2016 08:15 AM PDT

I am using gem differ https://github.com/pvande/differ

I have a helper

require 'differ'  module AnswersHelper      def self.getDiff (text1, text2)          Differ.format = :html          diff = Differ.diff_by_word(@current, @original)      end  end  

But I get an error No such file to load -- differ

If I remove require line I get an error at that line

Differ.format = :html  

uninitialized constant QuestionsController::Differ

When I tried following commands in rails console it worked

require 'differ'    diff = Differ.diff_by_word("text1","text2)  

I have gem differ in my gemfile and also I tried

require_relative 'differ'  

and

require './differ'  

UPD: seems restarting server helps, I'll check it right now

Rails gem Dragonfly default storage path changing

Posted: 22 Sep 2016 08:06 AM PDT

Dragonfly saves files under the (environment) directory, like:

public/system/dragonfly/development/  

or

public/system/dragonfly/production/  

is it possible to make the common directory and save all under (dragonfly) for production and development both?

public/system/dragonfly/  

How to manually add a column referencing a model in FactoryGirl?

Posted: 22 Sep 2016 07:56 AM PDT

I have the current modeling:

A House belongs_to User  A User has_one House  

Which means that the House model has a reference to User. My Factory for User, looks like this:

FactoryGirl.define do    factory :user do      house    end  end   

What this does is basically creating a User and a House that references that User.

Now, I have introduced a column in User called house_id and I want to be able to allow the Factory to work as it is, but also, fill the house_id with the House that was created. The reason why I am doing this is because I want to change the reference direction incrementally.

I have done it like this:

FactoryGirl.define do    factory :user do      house      house_id { House.find_by(user_id: id).id }    end  end   

But I suspect there might be a better way to do this. Any thoughts?

How does Phussion Passenger start Rails apps?

Posted: 22 Sep 2016 07:35 AM PDT

I'm moving my Unicorn+Nginx app to a Phussion Passenger docker image. Both passenger and nginx start up but the Ruby app itself not. What can be a possible cause? Any obvious places to look at?

The logs don't show anything useful (anything at all, really) and the ownership of the files is set to user running the app.

How can I call Action Mailer method for Postmark?

Posted: 22 Sep 2016 07:20 AM PDT

I've created server on postmarkapp.com. I,ve cheked the email sending by curl:

 curl "https://api.postmarkapp.com/email" \    -X POST \    -H "Accept: application/json" \    -H "Content-Type: application/json" \    -H "X-Postmark-Server-Token: my token" \    -d "{From: 'test@mydomen.tk', To: 'testemail@example.com', Subject: 'Hello from Postmark', HtmlBody: '<strong>Hello</strong> dear Postmark user.'}"  

It's worked,I've got letter.

I wanna send email from my rails application. I've written:

    class UserMailer < ApplicationMailer      def message      mail(        :subject => 'Hello from Postmark',        :to  => 'testemail@example.com',        :from => 'test@mydomen.tk',        :html_body => '<strong>Hello</strong> dear Postmark user!!!.',        :track_opens => 'true')    end  end          class UsersController < ApplicationController       def create      @user = User.new(user_params)        respond_to do |format|        if @user.save          #I try send message          UserMailer.message.deliver_now  # It doesn't work            format.html { redirect_to @user, notice: 'User was successfully     created.' }          format.json { render :show, status: :created, location: @user }        else          format.html { render :new }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end  

Also I've written in application.rb

class Application < Rails::Application      #postmark_settings      config.action_mailer.delivery_method = :postmark      config.action_mailer.postmark_settings = { :api_token => "my_token" }  end  

It's doesn't work. How need I call .message method?

Multiple Solr Instances - Second Solr Locked on Startup

Posted: 22 Sep 2016 07:22 AM PDT

I've been trying to figure out a workflow where my Minitest suite will launch a second Solr instance for feature tests even if the development instance is running. However, I'm running into issues just getting the servers to start (i.e. when I start them outside of testing).

To start my servers I'm using:

RAILS_ENV=development bin/rake sunspot:solr:start  RAILS_ENV=test bin/rake sunspot:solr:start  

However, whichever server starts second becomes locked. Any attempt to access the server in tests or just in development yields this error:

RSolr::Error::Http - 500 Internal Server Error  Error:     {msg=SolrCore 'test& 'is not available due to init failure: Index locked for write for core 'test'. Solr now longer supports forceful unlocking via 'unlockOnStartup'. Please verify locks manually!,trace=org.apache.solr.common.SolrException: SolrCore 'test' is not available due to init failure: Index locked for write for core 'test'. Solr now longer supports forceful unlocking via 'unlockOnStartup'. Please verify locks manually!      at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:974)      at org.apache.solr.servlet.HttpSolrCall.init(HttpSolrCall.java:250)      at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:417)      at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:214)      at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:179)      at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)      at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)      at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)      at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)      at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)    URI: http://localhost:8981/solr/test/update?wt=ruby  Request Headers: {"Content-Type"=>"text/xml"}  Request Data: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><add/>"  

I've searched around for issues related to locking but I can't find any where the problem is having two servers running. My setup is:

Rails (5.0.0.1)  sunspot (2.2.5)  sunspot_rails (2.2.5)  sunspot_solr (2.2.5)  ruby 2.3.1p112  

My sunspot.yml is:

production:    solr:      hostname: localhost      port: 8983      log_level: WARNING      path: /solr/production    development:    solr:      hostname: localhost      port: 8982      log_level: INFO      path: /solr/development    test:    solr:      hostname: localhost      port: 8981      log_level: WARNING      path: /solr/test  

And finally, solr.xml

<solr>      <solrcloud>        <str name="host">${host:}</str>      <int name="hostPort">${jetty.port:8983}</int>      <str name="hostContext">${hostContext:solr}</str>        <bool name="genericCoreNodeNames">${genericCoreNodeNames:true}</bool>        <int name="zkClientTimeout">${zkClientTimeout:30000}</int>      <int name="distribUpdateSoTimeout">${distribUpdateSoTimeout:600000}</int>      <int name="distribUpdateConnTimeout">${distribUpdateConnTimeout:60000}</int>      </solrcloud>      <shardHandlerFactory name="shardHandlerFactory" class="HttpShardHandlerFactory">      <int name="socketTimeout">${socketTimeout:600000}</int>      <int name="connTimeout">${connTimeout:60000}</int>    </shardHandlerFactory>    </solr>  

Thank you so much in advance!

Authentication failed Error when deploying to AWS EC2 AMI with Capistrano

Posted: 22 Sep 2016 06:58 AM PDT

I am following this tutorial:

https://www.sitepoint.com/deploy-your-rails-app-to-aws/  

The app is fully created and running in development (including the database). Keys have been added to GIT and SSH, although from the tutorial I am very sure which of them goes exactly where.

And this the error I am getting.

$ gem list net    *** LOCAL GEMS ***    net-http-digest_auth (1.4)  net-http-persistent (2.9.4)  net-scp (1.2.1)  net-ssh (3.2.0, 3.1.1)  net-telnet (0.1.1)  contactbook liviu-mac $ cap production deploy --trace  ** Invoke production (first_time)  ** Execute production  ** Invoke load:defaults (first_time)  ** Execute load:defaults  ** Invoke rvm:hook (first_time)  ** Execute rvm:hook  ** Invoke rvm:check (first_time)  ** Execute rvm:check  cap aborted!  Net::SSH::AuthenticationFailed: Authentication failed for user deploy@52.87.233.215  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/net-ssh-3.2.0/lib/net/ssh.rb:249:in `start'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/connection_pool.rb:59:in `call'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/connection_pool.rb:59:in `with'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/netssh.rb:155:in `with_ssh'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/netssh.rb:108:in `execute_command'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:141:in `block in create_command_and_execute'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:141:in `tap'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:141:in `create_command_and_execute'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:60:in `capture'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:9:in `block (3 levels) in <top (required)>'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:29:in `instance_exec'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/backends/abstract.rb:29:in `run'  /Users/liviu-mac/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sshkit-1.11.3/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'  Tasks: TOP => rvm:check  

I attempted almost all fixes suggested in the posts I found. Nothing works for me.

Here are more details:

$ gem list net    *** LOCAL GEMS ***    net-http-digest_auth (1.4)  net-http-persistent (2.9.4)  net-scp (1.2.1)  net-ssh (3.2.0, 3.1.1)  net-telnet (0.1.1)  

My Capfile is:

# Load DSL and set up stages  require "capistrano/setup"    # Include default deployment tasks  require "capistrano/deploy"    require 'capistrano/rvm'  # require 'capistrano/rbenv'  # require 'capistrano/chruby'  require 'capistrano/bundler'  require 'capistrano/rails/assets'  require 'capistrano/rails/migrations'  require 'capistrano/puma'  # require 'capistrano/passenger'  require 'capistrano/ssh_doctor'    # Load custom tasks from `lib/capistrano/tasks` if you have any defined  Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }  

My config/deply/production.rb file is (one single uncommented line):

server '52.87.233.215', user: 'deploy', roles: %w{web app db}  

And my config/deploy.rb file is:

# config valid only for current version of Capistrano  lock '3.6.1'    set :application, 'contactbook'  set :repo_url, 'git@github.com:levi-l-damian/contactbook.git'    # Default branch is :master  # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp  set :branch, :master    # Default deploy_to directory is /var/www/my_app_name  # set :deploy_to, '/var/www/my_app_name'  set :deploy_to, '/home/deploy/contactbook'    # Default value for :pty is false  set :pty, true    # Default value for :linked_files is []  # append :linked_files, 'config/database.yml', 'config/secrets.yml'  set :linked_files, %w{config/database.yml config/application.yml}    # Default value for linked_dirs is []  # append :linked_dirs, 'log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system'  set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}    # Default value for keep_releases is 5  set :keep_releases, 5    set :rvm_type, :user  set :rvm_ruby_version, 'ruby-2.3.1' # Edit this if you are using MRI Ruby    set :puma_rackup, -> { File.join(current_path, 'config.ru') }  set :puma_state, "#{shared_path}/tmp/pids/puma.state"  set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"  set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind  set :puma_conf, "#{shared_path}/puma.rb"  set :puma_access_log, "#{shared_path}/log/puma_error.log"  set :puma_error_log, "#{shared_path}/log/puma_access.log"  set :puma_role, :app  set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))  set :puma_threads, [0, 8]  set :puma_workers, 0  set :puma_worker_timeout, nil  set :puma_init_active_record, true  set :puma_preload_app, false  

Don't know how to fix this and move forward?

Rails Paperclip Heroku AWS DIsplay Image issue

Posted: 22 Sep 2016 07:27 AM PDT

I set up paperclip in a rails app and this worked fine locally and on heroku, however the images uploaded in posts were only saved in heroku for a short space of time. I set up an AWS account and created a bucket, and followed through the documentation to link my rails app to AWS to display images uploaded with paperclip. I have attached code snippets below. The images seem to be uploaded to AWS fine, however when I create a post, it says my post has been created successfully, however the image does not display, it just displays as a broken link. When I click image properties, it hs the AWS S3 url and upon looking in heroku logs, there are no known issues. I do not know why the image is not displaying.

config/environments/production.rb file:

# sets paperclip to upload images to Amazon S3    # Variables directed to heroku via the command line for pw etc    config.paperclip_defaults = {    storage: :s3,    s3_credentials: {      bucket: ENV.fetch('S3_BUCKET_NAME'),      access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),      secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),      s3_region: ENV.fetch('AWS_REGION'),    }  }

post.rb model file:

class Post < ApplicationRecord    extend FriendlyId    friendly_id :title, use: [:slugged, :finders]    has_attached_file :image, styles: { medium: "600x", thumb: "100x" }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/  end

show.html.erb file:

<div class="image">            <%= image_tag @post.image.url(:medium) %>          </div>

I have also set up heroku correctly using the following:

$ heroku config:set S3_BUCKET_NAME=your_bucket_name  $ heroku config:set AWS_ACCESS_KEY_ID=your_access_key_id  $ heroku config:set AWS_SECRET_ACCESS_KEY=your_secret_access_key  $ heroku config:set AWS_REGION=your_aws_region  

Any help would be appreciated.

Many thanks

No route matches [GET]

Posted: 22 Sep 2016 07:01 AM PDT

I'm trying to add 'add to cart' method for my items.

items_controller:

def to_cart    @item = Item.friendly.find(params[:id])     @item.add_to_cart    redirect_to root_path  end  

routes:

resources :items do    put :to_cart, on: :member  end  

model:

def add_to_cart    current_user.cart.items << self    current_user.cart.save  end  

show:

<%= @item.name  %>  <%= link_to 'add to cart', to_cart_item_path(@item) %>  

I got RoutingError: No route matches [GET] "/items/first/to_cart" 'first' because of friendly id. What I did wrong?

Rails: Is there an else statement in if try(:current_order)?

Posted: 22 Sep 2016 08:13 AM PDT

Is it possible to have an else statement in if try()?

The else block will be ignored:

          <% if try(:current_order) %>              <% if current_order.state != 'complete' && current_order.line_items.count > 0 %>              <%= current_order.line_items.count %>              <% end %>              <% else %>              <%= "&nbsp;".html_safe %>            <% end %>  

I want to achieve print out of &nbsp; if try(:current_order) fails.

UPDATE:

    <li class="icon icon-cart">        <%= link_to spree.cart_path do %>        <div class="cart">          <%= image_tag("shopping_bag.png", class: 'shopping-bag') %>          <span class="cart-items-count">            <% if current_order %>              <% if current_order.state != 'complete' && current_order.line_items.count > 0 %>                <%= current_order.line_items.count %>              <% end %>            <% else %>              &nbsp;            <% end %>          </span>        </div>        <% end %>      </li>  

I use this snippet in a header and when i open a static page where no current_order is available then i get:

NameError in Spree::Pages#show    undefined local variable or method `current_order' for #<#<Class:0x007fcd7636c090>:0x007fcd8770e0c0>  

Is there an easy fix without using try?

Ruby development on a virtual machine [on hold]

Posted: 22 Sep 2016 06:23 AM PDT

I want to learn ruby and ruby on rails. I'm using a windows machine. Someone told me I shouldn't develop ruby on a windows machine. I should develop ruby on linux or mac. So I became interested in virtual machines. I want to get VMWare and setup a linux virtual machine. I have a few questions before I do though. How much space does the virtual machine require? Is it like dual boot? If I use atom to write ruby code, can I run it in the VM? I have atom installed on computer. Will developing web applications be difficult on a VM? What should I know or be cautious about when using a VM?

Refind data when applying daterangepicker

Posted: 22 Sep 2016 06:18 AM PDT

An hour ago i get my first goal, to implement a datepicker and inserting its value to the database.

Now, on my Index I want to add a daterangepicker for filtering trough the events inserted in the database. I want to show the user only the events in his selected range, but I don't want the page to be reloaded every time he's applying a new date range. I did this in Meteor a few month ago and it was very easy because meteor just works really well as real-time framework.

Now I want to do the same with Ruby on Rails and I'm not sure how to do it. I red about actioncable / websockets. Do I need it for solving my problem, or is there a more simple way?

My idea (at the same time my question):

This is the callback function of my daterangepicker:

function(start, end, label) {            alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));          });  

So I thought may there is a way to recall the "index"-action in my controller, where I just have to do a simple @events = Events.where(date...) But I don't know if this is possible without a page reload. And if its not, is ActionCable the right thing to look at?

Really happy for every answer, thank you!

How to create search in my rails app? [on hold]

Posted: 22 Sep 2016 07:46 AM PDT

I reformulate my request a bit clearer I hope.

I have a rails app for suggesting tutorials. People can post tutorials in different categories (Categories were created in the console). Visitors and users can also consult any tutorials, but for an easier use I wish they could search by:

  • Categories
  • Users
  • Voted up

I don't know how to start, and if I have to modify anything in my app... You can have a look on the project online it may help you to see what I wanna do Thanks for your help

This my schema

ActiveRecord::Schema.define(version: 20160920133801) do      create_table "categories", force: :cascade do |t|      t.string   "name"      t.text     "description"      t.string   "image"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      create_table "tutos", force: :cascade do |t|      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.string   "title"      t.text     "content"      t.integer  "user_id"      t.integer  "category_id"    end      add_index "tutos", ["user_id"], name: "index_tutos_on_user_id"      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "first_name"      t.string   "last_name"      t.boolean  "admin"    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true      create_table "votes", force: :cascade do |t|      t.integer  "votable_id"      t.string   "votable_type"      t.integer  "voter_id"      t.string   "voter_type"      t.boolean  "vote_flag"      t.string   "vote_scope"      t.integer  "vote_weight"      t.datetime "created_at"      t.datetime "updated_at"    end      add_index "votes", ["votable_id", "votable_type", "vote_scope"], name: "index_votes_on_votable_id_and_votable_type_and_vote_scope"    add_index "votes", ["voter_id", "voter_type", "vote_scope"], name: "index_votes_on_voter_id_and_voter_type_and_vote_scope"    end  

ruby change color of label if conditional

Posted: 22 Sep 2016 07:03 AM PDT

I'am just start to learn code (and english .. ) and I have a prob with ruby conditional . :O

I have an array, " Category" who depending to "Publication" post.

and i would like that the color of label to my category change in fonction to catgeory ?

( sorry for my english i work for learn ^^ )

It's a part of my simple form for for post a product ( it 's false it's just for show my idea )

 <%= f.input :Category, collection:[" Application ", "Nature" ,"Design", "Science"], prompt: "Choisissez votre categorie"%>**  

Its a part of my index view to all my product

<% if Category["Nature"]? %>   <span class="label label-info">   <h6><%= publication.Category %></h6>  </span>  <% else if Category["Tech"]? %>   <span class="label label-sucess">  <h6><%= publication.Category %></h6>  </span>  <%end%>  

thx for help

Rails - Tool to generate migrations from class diagram

Posted: 22 Sep 2016 05:58 AM PDT

I've searched and found some tools to create the diagram class for models of a existing rails application. But what about the reverse? Is there anyway that I can draw the diagram class of my application and it generates the migrations? Thanks!

Using C# Interactive Console in Visual Studio 2015 as irb in RoR

Posted: 22 Sep 2016 05:40 AM PDT

I would like to use the C# Interactive Console as an easy way to interact with my database. In Ruby on Rails, one can talk with the database using ActiveRecord with irb. Recently, I noticed that there is a possibility to "execute in interactive" a piece of code in visual studio.

Is it possible to load the needed references to access the DB and use simple EF7 queries to interact with the database?

Carrierwave: main file on S3, thumb on local file system or in DB

Posted: 22 Sep 2016 05:23 AM PDT

In my Rails 3.2 project I use gem Carrierwave (0.8.0) to upload documents. My uploader also creates 2 document previews (icon: 64x64, preview: 256x256). I am able to configure Carrierwave to store all 3 files to S3 or to server's local file system.

Now I've got an optimization request: I should store main (large) document to S3 and its previews to file system or optionally to a database (MySQL).

Is there a way to implement it with Carrierwave??? Please, help...

Rails - link_to button to remove table row

Posted: 22 Sep 2016 06:08 AM PDT

I have a view in Rails 5 and was wondering if without using jQuery, I can remove a table row when clicking the button (here in the second column) ? If so, how?

<tr>    <td>Sample entry 12345</td>    <td colspan="2" style="text-align: right"><%= link_to '', annotation_path(@annotation), :class => "glyphicon glyphicon-remove" %></td>  </tr>  

Update

Before moving it to a separate function in the application JS, I wanted to test the suggested solution using plan JS. so, I added :onclick => "deleteRow(this)" to the button:

<td colspan="2" style="text-align: right"><%= link_to '', '', :class => "glyphicon glyphicon-remove", :onclick => "deleteRow(this)" %></td>  

yet nothing occurs. What is wrong?

Ignorance? it is a html table, not one created in the view by Rails or JS. Is that the reason?

Rails, current_page?(user_path) giving an error

Posted: 22 Sep 2016 05:28 AM PDT

I have element witch I want hide on specific pages, for example on pages located at app/views/users/ (there I have new.html.erb; edit.html.erb; show.html.erb. And I have div in my layouts/application.html.erb it will be shown on all pages, so I want to hide it.

I thought i can do it like this:

<% unless current_page?(new_user_path) || current_page?(user_path) %>    <div>Some content</div>  <% end %>  

But it will give me an error, pretty obvious: for user_show method he need an id of the user, but we are not visiting pages where variable @user is present. Can you land me a help:

  1. Any possibility to get around this error? (And I don't want to assign @user variable every where and I don't want make list of all page what are allowed)

  2. Is there any other way to hide element on specific pages?

Why my data won't save to SQL?

Posted: 22 Sep 2016 04:38 AM PDT

I'm quite new to Ruby on Rails. I'll just playing around with it. Actually, i'm trying to create a form with a title and a Daterangepick (bootstrap).

So, everything works fine until now. But i have one problem: My data don't save in the database. Everytime i submit the form it creates a new record, inserts automatically the "created_at" etc. But my two fields "title" and "date" are empty every time... i really don't know where my fault is. May someone of you can help me? Pls give me an answer with an explication, cause i'm really trying to understand whats going on.

Here is my code (I'm using simple_form gem)

new.html.erb:

<%= simple_form_for @event do |f| %>      <%= f.input_field :title, required: false %>      <%= f.input :date, input_html: { class: "daterange" }, required: false %>      <%= f.button :submit %>  <% end %>  <script type="text/javascript">    $(document).ready(function() {      $('input[class="string optional daterange"]').daterangepicker(          {            locale: {              format: 'YYYY-MM-DD'            },            startDate: '2013-01-01',            endDate: '2013-12-31'          },          function(start, end, label) {            alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));          });    });  </script>  

events_controller.rb:

class EventsController < ApplicationController      def index      @event = Event.all    end      def show      end      def new      @event = Event.new    end      def create      @event = Event.new(event_params)        if @event.save        redirect_to @event      else        render 'new'      end    end      private    def event_params      params.permit(:title, :date)      end  end  

I think this should be enough... for sure i can post more of my code if you wish, but i think the problem has to be here somewhere, since everything works fine... it routes fines, i can insert, it redirects me to /events/:id ... just the database keeps beeing empty. Thank you for your help !!!

Ignore protocol when caching with Rack::Offline

Posted: 22 Sep 2016 05:13 AM PDT

I'm caching a URL for offline browser usage with Rack::Offline, is it possible to change the protocol from HTTP to HTTPS depending on the request URL? Such as, if the request is http://localhost:3000, then the cache thing work with HTTP, and if the request is secure https://localhost:3000 the cache works with HTTPS. I think this is not possible but is there any way to do this?

#routes.rb  offline = Rack::Offline.configure do    cache "http://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"  end  

How to get path name of a file in Rails. [Rails 5.0]

Posted: 22 Sep 2016 05:05 AM PDT

i working on a rails script, and i need to get path name of the file uploaded, i did the same in Laravel recently, it was quite easy, here is the code i used at that time:

$img->getPathName();  

but i don't have any idea how to do the same in Rails.

If anybody knows then please let me know.

Thanks.

scrape json from viewsource page

Posted: 22 Sep 2016 07:38 AM PDT

So i'm trying to scrape json that exists in a website source and use it in my own site.

Heres an example site: view-source:http://www.viagogo.co.uk/Theatre-Tickets/Musicals/The-Lion-King/The-Lion-King-London-Tickets/E-1545516

If you look partway down there is a var eventListings

I would like to get all the code that exists in that var

So far all i have is this:

url = "http://www.viagogo.co.uk/Theatre-Tickets/Musicals/The-Lion-King/The-Lion-King-London-Tickets/E-1545516"   doc = open(url).read  

Any ideas how i can get this?

Thanks

Website for checking traffic fine (back-end) [on hold]

Posted: 22 Sep 2016 03:49 AM PDT

I'm front end developer. I want to make website which will check traffic fine by car number. User types Car ID Number and press check button. Then in the same page shows info about his car, registration date and etc. It needs databases obviously.

And admin page, where admin logs in with password, and can make changes to the databes, add, update,delete accounts(Car IDs).

I'am new in back-end. Please, guide me. It will amazing if you instruct me step by step, or give me some video tutorials.

Thanks.

Is it possible to this with javascript(angular.js)?

call config variables inside js in rails4

Posted: 22 Sep 2016 03:56 AM PDT

Hello I have include given file config/countries.rb

Shipping_10_14_days = ["AD", "AF", "AL", "AM", "AS", "AW", "AZ", "BA", "BB", "BM", "BS", "BZ", "CM", "CU", "CV", "DM", "DZ", "EE", "FK", "FM", "FO", "GF", "GL", "GY", "IS", "JM", "KG", "KY", "KZ", "LB", "LC", "LI", "LT", "MQ", "MU", "MV", "NA", "NU", "PA", "PF", "PY", "RO", "SV", "TD", "UA", "UG", "UZ", "ZM"]  Shipping_4_5_days = ["AE", "BD", "BH", "IR", "JO", "JP", "KH", "KW", "LA", "LK", "MM", "MO", "NF", "OM", "PH", "PK", "QA", "SA", "IN", "VN"]  Shipping_4_7_days = ["DK", "AT", "VI", "GB", "US"]  Shipping_5_7_days = ["BA", "BE", "BG", "CH", "CR", "CY", "CZ", "DE", "EG", "ES", "FI", "FR", "GE", "GH", "GL", "GR", "HN", "HR", "HU", "IE", "IL", "IT", "LU", "LV", "MA", "MC", "MN", "MT", "NA", "NC", "NG", "NL", "NO", "PL", "PT", "SE", "SK", "TR", "TW", "TZ", "ZA", "SG"]  Shipping_3_5_days = ["AU"]  Restricted_Country = ["AR", "BN", "BR", "BS", "CL", "CN", "CO", "CR", "EC", "FK", "GP", "GT", "GU", "ID", "IS", "MP", "MX", "NZ", "PE", "PM", "RS", "RU", "TH", "TT", "UY"]   

Now I want to call these variable inside my app/assets/javascripts/test.js Please guide me how to call these variables

function checkShippingDays(countryValue) {      var Shipping_10_14_days = ["AD", "AF", "AL", "AM", "AS", "AW", "AZ", "BA", "BB", "BM", "BS", "BZ", "CM", "CU", "CV", "DM", "DZ", "EE", "FK", "FM", "FO", "GF", "GL", "GY", "IS", "JM", "KG", "KY", "KZ", "LB", "LC", "LI", "LT", "MQ", "MU", "MV", "NA", "NU", "PA", "PF", "PY", "RO", "SV", "TD", "UA", "UG", "UZ", "ZM"]      var Shipping_4_5_days = ["AE", "BD", "BH", "IR", "JO", "JP", "KH", "KW", "LA", "LK", "MM", "MO", "NF", "OM", "PH", "PK", "QA", "SA", "IN", "VN"]      var Shipping_4_7_days = ["DK", "AT", "VI", "GB", "US"]      var Shipping_5_7_days = ["BA", "BE", "BG", "CH", "CR", "CY", "CZ", "DE", "EG", "ES", "FI", "FR", "GE", "GH", "GL", "GR", "HN", "HR", "HU", "IE", "IL", "IT", "LU", "LV", "MA", "MC", "MN", "MT", "NA", "NC", "NG", "NL", "NO", "PL", "PT", "SE", "SK", "TR", "TW", "TZ", "ZA", "SG"]      var Shipping_3_5_days = ["AU"]      var Restricted_Country = ["AR", "BN", "BR", "BS", "CL", "CN", "CO", "CR", "EC", "FK", "GP", "GT", "GU", "ID", "IS", "MP", "MX", "NZ", "PE", "PM", "RS", "RU", "TH", "TT", "UY"]         if ($.inArray(countryValue, restrictedCountry) > -1) {        alert('we don not ship in this country')        $('.adress-next').prop('disabled', true);      } else{        $('.adress-next').prop('disabled', false);        if ($.inArray(countryValue, shipping10to14) > -1) {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 10-14 business days)')        } else if ($.inArray(countryValue, shipping4to7) > -1) {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 4-7 business days)')        } else if ($.inArray(countryValue, shipping4to5) > -1) {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 4-5 business days)')        } else if ($.inArray(countryValue, shipping3to5) > -1) {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 3-5 business days)')        } else if ($.inArray(countryValue, shipping5to7) > -1) {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 5-7 business days)')        } else {          $('.shipping-days').html('<strong>FREE</strong> Delivery (average 4-7 business days)')        };      };    };  

I need to call these variables inside js file.

No comments:

Post a Comment