Saturday, June 11, 2016

Validation doesn't work as expected for related models in Rails 4? | Fixed issues

Validation doesn't work as expected for related models in Rails 4? | Fixed issues


Validation doesn't work as expected for related models in Rails 4?

Posted: 11 Jun 2016 05:38 AM PDT

I use one form to enter data for two models. When I save parent model (Tenant) the child model (User) also gets saved, but only if I don't validate tenant_id in User model. If I do validates :tenant_id, presence: true in User model then validation error "Users tenant can't be blank" is displayed. Any ideas why?

Tenant model:

class Tenant < ActiveRecord::Base      has_many :users, dependent: :destroy, inverse_of: :tenant    accepts_nested_attributes_for :users          before_validation do       self.status = 0       self.name = name_orig.upcase       email.downcase!    end      validates :name_orig, presence: true, length: { maximum: 255 }      validates :name, uniqueness: { case_sensitive: false }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i    validates :email, presence: true, length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }      validates :status, presence: true    end  

User model:

class User < ActiveRecord::Base      belongs_to :tenant, inverse_of: :users    validates_presence_of :tenant      before_validation do       self.status = 0      self.email = email.downcase    end      VALID_USERNAME_REGEX = /\A\w+\s?\w*\z/i    validates :name,  presence: true, length: { maximum: 50 },                      format: { with: VALID_USERNAME_REGEX },                      uniqueness: { case_sensitive: false }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i    validates :email, presence: true, length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }      has_secure_password    validates :password, presence: true, length: { minimum: 6 }      validates :tenant_id, presence: true      validates :status, presence: true    end  

Tenant controller:

class TenantsController < ApplicationController      def new      @tenant = Tenant.new      @tenant.users.build    end      def create              @tenant = Tenant.new(tenant_params)      @tenant.save        if @tenant.save        flash[:success] = "Welcome!"        redirect_to @tenant   # redirects to tenant profile      else        render 'new'      end    end        private        def tenant_params        params.require(:tenant).permit(:name_orig, :email,            users_attributes: [:name, :email, :password, :password_confirmation])      end    end  

Pundit scoping usage empty results

Posted: 11 Jun 2016 05:36 AM PDT

Suppose I have a scenario where we have Users and each user can create their own Projects.

I'm trying to limit the Show action of my Rails controller to only allow admin or the owner of the project to be able to go through Show action.

The problem I am facing is, perhaps I'm misunderstanding on how to use Scopes in Pundit.

My Show action looks like this:

  def show      project = policy_scope(Project).find_by({id: project_params[:id]})        if project        render json: project      else        render json: { error: "Not found" }, status: :not_found      end    end  

My Pundit Scope class looks like this:

  class Scope < Scope        def resolve        if @user.admin?          scope.all        else          # obviously, if non-matching user id, an ActiveRelation of            # empty array would be returned and subsequent find_by(...)           # would fail causing my controller's 'else' to execute          # returning 404 instead of 403          scope.where(user_id: @user.id)        end      end    end  

In my Rails test, I am trying to assert that non-project owner should receive a 403 forbidden:

test "show project should return forbidden if non admin viewing other user's project" do    # "rex" here is not the owner of the project    get project_path(@project.id), headers: @rex_authorization_header    assert_response :forbidden  end  

My test is failing. I am getting the error:

Failure:  ProjectsControllerTest#test_show_project_should_return_forbidden_if_non_admin_viewing_other_user's_project [/Users/zhang/App_Projects/LanceKit/Rails_Project/LanceKit/test/controllers/projects_controller_test.rb:40]:  Expected response to be a <403: forbidden>, but was a <404: Not Found>.  Expected: 403    Actual: 404  

I don't quite feel like I'm using Pundit correctly.

Should I be using Pundit's authorize project instead of using policy_scope(Project)... for the Show action?

I was expecting the scope.where(...) to detect the incorrect user id and return some error saying 'you are not authorized to view this resource' rather than returning results.

Rails + Angular JS + Socket IO

Posted: 11 Jun 2016 05:13 AM PDT

I try to connect my Grape API + Angular JS to socket.io and I have got some errors, preventing me to do it. Can you please help me?

I have downloaded this client https://github.com/socketio/socket.io-client.

And also this plugin https://github.com/btford/angular-socket-io.

Added to my app.js dependency 'btford.socket-io'.

And created factory

app.factory('socket', function ($rootScope) {    var socket = io.connect();    return {      on: function (eventName, callback) {        socket.on(eventName, function () {            var args = arguments;            $rootScope.$apply(function () {              callback.apply(socket, args);            });          });        },      emit: function (eventName, data, callback) {        socket.emit(eventName, data, function () {          var args = arguments;            $rootScope.$apply(function () {              if (callback) {                callback.apply(socket, args);              }            });          })        }      };    });  

But I continue to get same error:

ActionController::RoutingError (No route matches [GET] "/socket.io")

I did not include line

script src="/socket.io/socket.io.js"

I included only

socket.js and socket.io.js to my lib

Create Metafield for product in shopify rails

Posted: 11 Jun 2016 05:00 AM PDT

I am new to shopify application development and working on to create app which add time block on product page.

I have created rails app with form on home#index page as below

<%= form_tag('/home/save_product_options', id: "form_#{product.id}", 'data-shopify-app-submit' => 'unicorn_form_submit') do %>    <%= hidden_field_tag :key %>    <%= hidden_field_tag :product_id, product.id %>    <%= hidden_field_tag :value %>    <%= check_box_tag :product_timer, false, false, onclick: "add_key_value('#{product.id}')" %> Add timer to product <br>    <%= submit_tag 'Save', disabled: true %>  <% end %>  

So when admin select checkbox and submit, a metafield should be created for above product.

But it always return error 500 on form submit even though save_product_options path exists in application

Please suggest any direction

subqueries as columns in select same table but different condition and result

Posted: 11 Jun 2016 05:03 AM PDT

I have two tables

#orders  | id | item_id | quantity | ordered_on |  |----|---------|----------|------------|  |  1 |    1    |    2     | 2016-03-09 |  |  2 |    1    |    2     | 2016-03-12 |  |  3 |    4    |    3     | 2016-03-15 |  |  4 |    4    |    3     | 2016-03-13 |    #stocks  | id | item_id | quantity | enter_on   | expire_on  |  |----|---------|----------|------------|------------|  |  1 |    1    |   10     | 2016-03-07 | 2016-03-10 |  |  2 |    1    |   20     | 2016-03-11 | 2016-03-15 |  |  3 |    1    |   20     | 2016-03-14 | 2016-03-17 |  |  4 |    4    |   10     | 2016-03-14 |    NULL    |  |  5 |    4    |   10     | 2016-03-12 |    NULL    |  

So I'm trying to create a view to show the orders along with its closest stocks enter_on like this (I'm using include_after and include_before to give an overview on which date I want to exclude the item that's preordered, so the stock would reflect correctly)

include_after is always going to be the stock that came in but not expired yet, if expired, show NULL, include_before will always show the next incoming stock enter_on, unless there's an expire_on that's earlier than the next enter_on

| item_id | quantity | ordered_on | include_after | include_before |  |---------|----------|------------|---------------|----------------|  |    1    |    2     | 2016-03-09 |  2016-03-07   |   2016-03-10   |  |    1    |    2     | 2016-03-12 |  2016-03-11   |   2016-03-14   |  |    4    |    3     | 2016-03-13 |  2016-03-12   |   2016-03-14   |  |    4    |    3     | 2016-03-15 |  2016-03-14   |      NULL      |  

So this is what I came up with

SELECT    o.item_id, o.quantity, o.order_on, (      SELECT COALESCE(MAX(s.enter_on), NULL::DATE)      FROM stocks s      WHERE s.enter_on <= o.order_on AND s.item_id = o.item_id    ) as include_after, (      SELECT COALESCE(MIN(s.enter_on), NULL::DATE)      FROM stocks s      WHERE s.enter_on > o.order_on AND s.item_id = o.item_id    ) as include_before  FROM    orders o  

It works fine (I haven't included the expire_on part), but I'm worrying about performance issue for using two subqueries in the select.

Does anyone have some alternative suggestions?

Let me know if the question is unclear, the problem is a bit chaotic.

Thanks!

rails nginx and puma error

Posted: 11 Jun 2016 04:44 AM PDT

I've just deployed a new app and got some errors. my config files looks like the ones in here: https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma

puma log:

    === puma startup: 2016-06-11 13:10:07 +0200 ===  ! Unable to load application: Errno::EADDRINUSE: Address already in use - bind(2) for [::]:2010  bundler: failed to load command: puma (/home/admrails/apps/Paris/shared/bundle/ruby/2.1.0/bin/puma)  

nginx log:

    2016/06/11 13:16:37 [crit] 29360#0: *3 connect() to unix:///home/admrails/apps/myapp/shared/tmp/sockets/Paris-puma.sock failed (2: No such file or directory) while connecting to upstream, client: 127.0.0.1, server: myIP, request: "GET /en/log_in HTTP/1.1", upstream:     "http://unix:///home/admrails/apps/myapp/shared/tmp/sockets/myapp-puma.sock:/en/log_in", host: "localhost"  

Any idea ? Tkx

Rails / Shared strong parameters' definition between two controllers

Posted: 11 Jun 2016 05:53 AM PDT

having two items_controller, one for the api (in app/controllers/api/) and one for the backend (in app/controllers/backend)

The strong parameters are quite long (20 fields or something) and prompt to evolve a bit. That would not be impossible to maintain this list in both controllers, but as the needs are more or less the same on the create/updates actions, I'd be looking into sharing the strong parameters definition in a separate file that would be shared to both

I've tried to inherit those two with a super controller including only the strong parameter definition :

class SharedItemsController < ApplicationController    private # not knowing all the prerequisites of this, I tried also using protected instead of private; same result       def item_params         ....      end    end  end  class  Frontend::ItemsController < SharedItemsController     ...  end  class  Api::ItemsController < SharedItemsController     ...  end  

No success, I'm stuck with unpermitted parameters

Hope to get some tips on this one here on SO; best

How to elegantly return hash with one value modified in Ruby?

Posted: 11 Jun 2016 04:51 AM PDT

I have this method in Rails that returns params:

def customer_params    params.require(:treatment_booking).require(:customer)  end  

I want to remove whitespace from :phone in place and return the whole hash. I can do it like so:

params.require(:treatment_booking).require(:customer).merge(:phone => params[:treatment_booking][:customer][:phone].gsub(/\s+/, ""))  

.. but I think it's a bit not elegant since I have to reference the whole path to a hash that I already calling methods on. Is there a better way?

I think this is Ruby question, but Rails answer would be just as valid.

How to access spree commerce website from external IP address on google compute engine

Posted: 11 Jun 2016 04:31 AM PDT

I am new to Ruby/Rails/Spreecommerce but eventually following the tutorials that I can find on the internet, I successfully made the Spree commerce shop website on localhost:3000. I am using Google Cloud Platform (GCP) for this custom VM: CentOS7, Apache, MySQL, PHP7, Ruby latest, Rails latest, VNC server to access the VM etc.

My question is, How do I access my shop with external w.x.y.z IP that GCP has assigned me? When I access this IP from outside I get the usual Apache working Test page ok (assume on default port 80?). I believe Apache server is running too along with rails server.

Currently on VM only, I have the access to localhost:3000 which shows my website perfectly ok.

Am I missing some config to tweak, so that the outside world can access on w.x.y.z IP? Once this works then I plan to change the nameservers for my actual domain.

I had a look at the pre-made solution like Bitnami Spree but I keep away from branding usually hence using my own CentOS7 from scratch. thanks!

How to connect two tables by using ActiveRecord?

Posted: 11 Jun 2016 05:29 AM PDT

I'm trying RoR Active Records with Association. And trying to connect two tables, which is restaurants and restaurant_translations. These are split for multi-language support.

Here's the definition of those two tables.

class CreateRestaurants < ActiveRecord::Migration    def change      create_table :restaurants do |t|        t.string :restaurant_id        t.string :type        t.string :genre        t.string :url        t.string :fb        t.string :mailaddr          t.timestamps null: false      end    end  end    class CreateRestaurantTranslations < ActiveRecord::Migration    def change      create_table :restaurant_translations, {:id => false}  do |t|        t.integer :id        t.string :restaurant_id        t.string :name        t.string :address        t.string :tel        t.text :description        t.string :lang          t.timestamps null: false      end      execute "ALTER TABLE restaurant_translations ADD PRIMARY KEY (id,lang);"    end  end  

And the Models.

class Restaurant < ActiveRecord::Base          has_many :restaurant_translations  end     class RestaurantTranslation < ActiveRecord::Base          self.table_name = 'restaurant_translations'          belongs_to :restaurant  end  

And then here's the controller which creates my headache.

class RestaurantController < ApplicationController          def list                  @restaurants = Restaurant.all                  @restaurants = @restaurants.restaurant_translation.find_by(lang: "en")          end  end  

So error shows like this. Could you tell me how to write?

enter image description here

@Pavan 's advice causes some another errors like this.

enter image description here

BTW, my view is like this. It's .slim file.

h1 = t :restraunt_list_title    table    thead      tr        th = t :restraunt_list_type        th = t :restraunt_list_name        th = t :restraunt_list_url        th = t :restraunt_list_genre        th = t :restraunt_list_addr      tbody      - @restaurants.each do |restaurant|        tr          td = restaurant.restaurant_type          td = restaurant.restaurant_translations.first.restaurantname          td = link_to 'here', restaurant.url          td = restaurant.genre          td = restaurant.restaurant_translations.first.address      br  

The bucket you are attempting to access must be addressed using the specified endpoint

Posted: 11 Jun 2016 04:22 AM PDT

I'm using paperclip 5.0.0.beta2 in my latest rails (4.2.6) project. The application is hosted on Heroku. I can upload an image and it seems to be stored in a bucket on Amazon S3. However in the browser the image appears to have a broken url, although it's point to the bucket on Amazon S3, the url is:

http://s3.amazonaws.com/gigbnb/profiles/profile_pics/000/000/002/small/anthony_candaele-300x300.jpg?1464956858

When I enter this url in the browser, I get an xml page with this error message:

The bucket you are attempting to access must be addressed using the     specified endpoint. Please send all future requests to this endpoint.  

It looks like there is an issue with the S3 endpoint.

However I set the region (eu-west-1) in configuration file:

config/environments/production.rb      config.paperclip_defaults = {     storage: :s3,     s3_region: ENV.fetch('AWS_REGION'),     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'),     }  }  

My Github repository is at:

https://github.com/acandael/gigbnb

Does anyone have an idea what's going on?

Thanks for your help,

Anthony

How can I make a dropdown menu in rails with the option to display an image?

Posted: 11 Jun 2016 04:21 AM PDT

I want to make a simple dropdown menu which lists some options (for example: tiger and lion). When I press the submit button, i want to reload the page, the dropdown menu should be still there and the image of one of the options (images are in app/assets/images) should be below.

I don´t know how to define the change action in the controller, that after pressing the submit button, the page reloads and the correct image is shown. Also i am not quite sure if my dropdown menu is correct. I would be very glad if you have some ideas. Thanks in advance.

This is my view so far:

<h1>Animals</h1>    <%=form_tag change_animals_path do %>    <select>      <option>lion</option>      <option>tiger</option>    </select>        <%= submit_tag "Switch Animal", class: "btn btn-lg btn-first"%>    <% end %>  <br>      <div align="center">        <img src="/assets/<%= @images_t %>">      </div>    </div>  

This view has a dropdown menu and shows the tiger image. This is the def index of the animals controller:

def index  @images_t = ("tiger.jpg")  @images_l = ("lion.jpg")  end    def change  ?????  redirect_to  animals_path  end  

Rails 4 ActiveRecord Exclusion Validation for Association

Posted: 11 Jun 2016 05:15 AM PDT

I'm trying to validate an association in my model and exclude a certain object for the validation, but can't seem to get it to work. Here's my code:

validates :user, presence: true, exclusion: { in: [:lot_high_bidder] }  

I imagine it's trying to do a direct comparison of :user with the symbol :lot_high_bidder which will obviously always fail, but does that mean I can't use a method name in an exclusion validator or is the syntax just wrong?

Should i make a seperate app to send push notifications to 40-50k users in RoR App or use background jobs

Posted: 11 Jun 2016 05:12 AM PDT

I have a rails application that is in fact a backend of a popular IOS application which have a user base of 200k users who need to be notified time to time.

Daily 40-50k users will be notified using push notifications. These push notifications will be realtime and scheduled ones. eg: if a new users signs up he will be notified within few seconds. eg: scheduled notifications will run at 10 pm daily with limited users ranging 10k-30k or sometimes more upto 100k.

I also will be doing business reporting to generate list of users fulfilling certain criteria and it requires firing mysql queries that could take upto 1-2 minutes of time.

My area of concern is should i have a seperate application with seperate mirror db to send push notifications to these users so my IOS users doesnt feel lag while using this application when push notifications are triggered or business reporting query is triggered.

Or should i use background jobs like Rails Active job, Sidekiq or Sucker Punch to perform push notifications and triggering business reporting queries.

Is background jobs in rails so powerful that it can manage this condition and doesn't let App users to feel lag in experience.

My application stack is:

Rails: 4.1.6  Ruby: 2.2  DB: Mysql  PaaS: AWS Elastic Beans  IOS Push gem: Houston  

Ruby on rails - Simple form not displaying errors for radio select. Other errors display fine

Posted: 11 Jun 2016 03:56 AM PDT

I have a user registration form (Devise) with 4 elements; Username, email, password and 'user type'. User type is a boolean and is displayed as a radio select on the form.

Errors for Username, email and password show no problem, but I get no errors showing if a user doesn't select one of the radio buttons. Validation IS in place, and the form won't send without one of the radio buttons selected, but I get no errors.

The form:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>              <%= f.error_notification %>          <div class="role-selector">              <p class="type-sel-txt"><%= t('front.whattype') %></p>              <label for="artistuser">                  <%= f.radio_button :artist, "1", :id => "artistuser" %>                  <span class="artistuser-sel"><%= t('front.bandm') %></span>              </label>              <label for="eventuser">                  <%= f.radio_button :artist, "0", :id => "eventuser" %>                  <span class="eventuser-sel"> <%= t('front.evento') %></span>              </label>          </div>          <%= f.input :username, required: true, autofocus: true, placeholder: t('forms.login.user'), label: false %>          <%= f.input :email, required: true, placeholder: t('forms.login.email'), label: false %>          <%= f.input :password, required: true, placeholder: t('forms.login.password'), label: false %>          <div id="passcheck"></div>          <%= f.button :submit, t("forms.login.signup"), id: "register-btn" %>      <% end %>  

User.rb:

  validates_inclusion_of :artist, in: [true, false], on: :create  

Registration works without a problem, my only issue is the error not showing. I'm not sure if it is necessary to paste any more of my code, but if so I'll update with whatever is required.

Time in DB compared to current time

Posted: 11 Jun 2016 03:00 AM PDT

I have a couple of stores that I'd like to display if they're open or not.

The issue is that I have my current time.

Time.current  => Sat, 11 Jun 2016 11:57:41 CEST +02:00  

and then if I for example take out the open_at for a store I get:

2000-01-01 00:00:00 +0000  

so what I have now is:

  def current_business_hour(current_time: Time.current)      business_hours.where('week_day = ? AND open_at <= ? AND close_at >= ?',                           current_time.wday, current_time, current_time).first    end  

and then I check if a current_business_hour is present. However this is calculating it wrong by what seems like two hours. The open_at and close_at should be within the time zone of Time.current.

Can't install rails-assets-tether

Posted: 11 Jun 2016 02:50 AM PDT

When I try to install rails-assets-tether, I get an error.

Retrying fetcher due to error (2/4): Bundler::Fetcher::CertificateFailureError Could not verify the SSL certificate for http://rails-assets.org/.  There is a chance you are experiencing a man-in-the-middle attack, but most likely your system doesn't have the CA certificates needed for verification. For information about OpenSSL certificates, see http://------/ruby-ssl. To connect without using SSL, edit y  our Gemfile sources and change 'https' to 'http'.  

This is the part of my Gemfile:

# Bootstrap  gem 'bootstrap', '~> 4.0.0.alpha3'  source 'https://rails-assets.org' do    gem 'rails-assets-tether', '>= 1.1.0'  end  

Changing https to http didn't work for me.

I'm using Windows 10

Foundation CSS with Rails - restricting certain JS elements from loading

Posted: 11 Jun 2016 01:52 AM PDT

Foundation is a great CSS framework, but when used with Rails as a gem it loads up a lot of unnecessary js elements, such as accordions, etc:

GET /assets/foundation/foundation.alert.js  GET /assets/foundation/foundation.js  GET /assets/foundation/foundation.abide.js  GET /assets/foundation/foundation.accordion.js  GET /assets/foundation/foundation.clearing.js  GET /assets/foundation/foundation.dropdown.js  GET /assets/foundation/foundation.joyride.js  GET /assets/foundation/foundation.interchange.js  GET /assets/foundation/foundation.magellan.js  GET /assets/foundation/foundation.reveal.js  GET /assets/foundation/foundation.offcanvas.js  GET /assets/foundation/foundation.tab.js  GET /assets/foundation/foundation.orbit.js  GET /assets/foundation/foundation.topbar.js  GET /assets/foundation/foundation.slider.js  GET /assets/foundation/foundation.tooltip.js  GET /assets/foundation.js  GET /assets/foundation/foundation.equalizer.js  

I would like to find a way to get in the middle of this process and remove a bunch of these elements to get a small performance boost. I understand that I need to swap the

//= require foundation  

line in my application.js file with the list of the elements I need but I am having trouble finding such list and its correct spelling.

I cannot get assets to work in Rails application

Posted: 11 Jun 2016 02:14 AM PDT

I just fixed some problems with database in production mode of my Rails application and now I couldn't get any assets to work. Here is the part of production.log:

    I, [2016-06-11T10:26:14.368556 #4807]  INFO -- : Started GET "/assets/application-dcd31064dda15c4420c78914a108b57fe4a17ea71a20e180b4d51e1f12c45c7a.js" for 127.0.0.1 at 2016-06-11 10:26:14 +0200  F, [2016-06-11T10:26:14.375224 #4807] FATAL -- :   ActionController::RoutingError (No route matches [GET] "/assets/application-dcd31064dda15c4420c78914a108b57fe4a17ea71a20e180b4d51e1f12c45c7a.js"):    actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'    railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'    railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'    railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'    rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'    rack (1.6.4) lib/rack/runtime.rb:18:in `call'    activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'    rack (1.6.4) lib/rack/sendfile.rb:113:in `call'    railties (4.2.6) lib/rails/engine.rb:518:in `call'    railties (4.2.6) lib/rails/application.rb:165:in `call'    rack (1.6.4) lib/rack/lock.rb:17:in `call'    rack (1.6.4) lib/rack/content_length.rb:15:in `call'    rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'    /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'    /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'    /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'  

I have app/assets/javascript/application.js and app/assets/stylesheet/application.scss because of Bootstrap. I tried with precompiling assets for production environment and still nothing.

app/assets/stylesheet/aplication.scss

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   * listed below.   *   * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,   * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.   *   * You're free to add application-wide styles to this file and they'll appear at the bottom of the   * compiled file so the styles you add here take precedence over styles defined in any styles   * defined in the other CSS/SCSS files in this directory. It is generally better to create a new   * file per style scope.   *   *= require styles   */    @import "bootstrap-sprockets";  @import "bootstrap";  @font-face{  font-family:'Glyphicons Halflings';  src: font-url("bootstrap/glyphicons-halflings-regular.eot");  src: font-url("bootstrap/glyphicons-halflings-regular.eot?#iefix") format("embedded-opentype"),  font-url("bootstrap/glyphicons-halflings-regular.woff") format("woff"),  font-url("bootstrap/glyphicons-halflings-regular.ttf") format("truetype"),  font-url("bootstrap/glyphicons-halflings-regular.svg#glyphicons_halflingsregular") format("svg")  }  

Cannot generate anything because of Devise [duplicate]

Posted: 11 Jun 2016 01:27 AM PDT

This question already has an answer here:

When I try to use any generator I get an error from devise:

C:\Users\dukei\RubymineProjects\alnair>rails g model product  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.0.rc1/lib/active_record/dynamic_matchers.rb:21:in `method_missing': undefined method `devise' for User (call 'User.connection' to establish a connection):Class (NoMethodError)  

It started after I created User model with rails g devise USER

How do I solve it?

coffeescript class - calling calling one class method from an other

Posted: 11 Jun 2016 01:14 AM PDT

I have rewritten my embedded JS in my rails app to coffeescript..and I am new to coffeescript...

My approach is a mix of these articles:

My code:

s = undefined  class App.PhotoLike      settings:      modalElement: $('#myModal')      likeButtonId: '#like'      photo_id: $('.image_info').attr('photo_id')      numberOfLikes: $('#likes_num')      constructor: (@el) ->      console.log('constructor called')      s = @settings      @bindUIActions()      return this        bindUIActions: ->      console.log('bindUIActions called')      $('#myModal').on 'click', '#like', -> likePhoto()      $(document).on "page:change", -> pageChange()        pageChange: ->      console.log('pageChange called')      photo = new App.Photo      likePhoto: ->      console.log('likePhoto called')      url = '/photos/' + s.photo_id + '/like'      $.get url, (data) ->        s.numberOfLikes.html data['likes'] + ' likes'        $(s.likeButtonId).toggleClass 'btn-success'  

This is part of a model that gets loded with ajax and once that call succeeds i do i create the above class (instance of):

new (App.PhotoLike)  

My problem. The modal gets loaded an all seems good. But when I trigger the event:

$('#myModal').on 'click', '#like', -> likePhoto()  

I get:

photo.like.self-942fcd8….js?body=1:25 Uncaught ReferenceError: likePhoto is not defined  

so, it does not know the likePhoto function. I have tried calling this.likePhoto and @likePhoto, but this refers to the button element that triggers the event.

So how do I do this? Other approaches are welcome. i not really sure that I need the classes...but I really want structured code...

When I run Rails Console it says "Switch to inspect mode"

Posted: 11 Jun 2016 01:45 AM PDT

If I try to access my console or irb git bash says "switch to inspect mode". I followed the answers here & tried installing the readline gem(0.5.3)(ended without any luck) linked here : https://rubygems.org/gems/rb-readline/versions/0.5.3

rb-readline gem installed

I'm unable to access the console or irb.

Ruby: Confused about how to make sense of this code

Posted: 11 Jun 2016 02:07 AM PDT

I'm a little confused about one part of this code. In line 7 I have commented below.

01:states_file = File.open("states_abbrev.txt")  02:states = {}  03:while ! states_file.eof?  04:     first = states_file.gets.chomp  05:     #"ALABAMA,AL"  06:     data = first.split(",")  07:     states[ data[0] ] = data[1] #This line here.  08:end  09:puts states.inspect  10:  11:states_file.close  

Line 5 is and example of what each line is like in the states_abbrev.txt file. Just a state, a comma, abbreviation, and a carriage return. All 50 states are in the file.

As you can see on line 7 the data[0] key seems to be overwritten by data[1]. So why is it when i run this code data[0] is still the key, and data[1] becomes the value?

create table rows of 4 in rails

Posted: 11 Jun 2016 01:18 AM PDT

I have these checkboxes, I'm trying to create rows of 4 checkboxes. At the moment it creates one row.

<table>    <%= f.collection_check_boxes :expertise_ids, Expertise.all, :id, :name do |b| %>        <td>          <label style="margin-left:5px; margin-right:15px;" class="checkbox-inline">           <%= b.check_box %>           <%= b.label %>          </label>        </td>    <% end %>  </table>                   

Iv have tried something like this:

<table>    <%= f.collection_check_boxes :expertise_ids, Expertise.all, :id, :name do |b| %>      <% tablerows = 0 %>        <td>          <label style="margin-left:5px; margin-right:15px;" class="checkbox-inline">           <%= b.check_box %>           <%= b.label %>           <% tablerows += 1 %>           <% break if tablerows == 3 %>          </label>        </td>    <% end %>  </table>  

Im trying something like this to iterate over and every time is counts to 4 in trying to generate a new row, but I'm not sure how to complete this.

webrick using ssl whats to do?

Posted: 11 Jun 2016 12:36 AM PDT

I've got a rails 4 application and I want to run it with SSL on webrick. what do I have to do?

I've added the ssl certificate for the domain and startet like this

bundle exec rails s -e production -p 3001 --binding=0.0.0.0

Now I got this error:

Internal Server Error    The server encountered an internal error or misconfiguration and was unable to complete your request.    Please contact the server administrator at  to inform them of the time this error occurred, and the actions you performed just before this error.    More information about this error may be available in the server error log.    Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.    Apache Server at domain.de Port 443  

Thanks

ruby on rails: how to add Device

Posted: 11 Jun 2016 12:34 AM PDT

I want to get rid from unwanted users using Ruby on Rails. There are several options to do this using Device. How to add Device to Ruby on Rails? thanks.

Rails change root-path

Posted: 11 Jun 2016 12:13 AM PDT

I have thingspeak server working on http://portail.lyc-st-exupery-bellegarde.ac-lyon.fr/srv3, witch is behind a proxy server.

how can i tell rails to add "srv3/" to all url ?

/srv3 should be the root.  

thanks

moving rails2 to 4 and getting error - undefined method `with_scope'

Posted: 11 Jun 2016 01:22 AM PDT

How to replace this Query in rails4.1.9

   AuditArea.send(query_options[:include_retired] ? :with_exclusive_scope :  :with_scope) {         # some stuff    }  

Getting Error undefined method `with_scope' .

How do I model Child belongs to class

Posted: 10 Jun 2016 11:31 PM PDT

create_table "children", force: :cascade do |t|      t.string   "name"      t.date     "dob"      t.string   "child_class"      t.string   "section"      t.integer  "parent_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end  

This is the schema I have for the Child model. child_class values are getting stored as "1", "2" .. "12".

Should I need to create 12 different models, from Class1 to Class12 and all will have belongs_to Child class? Is there an efficient way to to do this?

Rails Ajax dropdown menu - no response

Posted: 10 Jun 2016 11:38 PM PDT

So I've solved almost all my problems with this little program I'm writing:

The only one left, that I'm just beating my head against, goes like this.

It's your standard two dropdown menus, select an item on one to populate the other.

In my view:

<%=     select_tag(          :contractor_id,        options_from_collection_for_select(Contractor.all, "id", "appointment_record"),         :'data-remote' => 'true',         :'data-url' => url_for(:controller => 'contractors', :action => 'getdata'),         :'data-type' => 'json')   %>      <%=      select_tag(         :company_id, # name of selectbox         )  %>   

In my controller:

    def getdata      @data_from_select1 = params[:contractor_id]        @data_for_select2 = Company.where(:id => @data_from_select1).all        # render an array in JSON containing arrays like:      # [[:id1, :name1], [:id2, :name2]]      render :json => @data_for_select2.map{|c| [c.id, c.name]}    end  

In my application.js:

$(document).ready(function() {      $('#contractor_id').live('ajax:success', function(evt, data, status, xhr) {        var selectbox2 = $('#company_id');        selectbox2.empty();        $.each(data, function(index, value) {        // append an option        var opt = $('<option/>');          // value is an array: [:id, :name]        opt.attr('value', value[0]);        // set text        opt.text(value[1]);        // append to select        opt.appendTo(selectbox2);      });    });  });  

In my routes:

   get 'getdata' => 'contractors#getdata'  

And I just don't get anything at all populating company.id. Not ever!

Contractor.id populates just fine, all the names fill out there, but nothing is returned to company.id

I'm a huge noobie, so I'm sure I'm missing something here. What??

No comments:

Post a Comment