Friday, May 13, 2016

Select option from dropdown menu and show list based on option chosen rails | Fixed issues

Select option from dropdown menu and show list based on option chosen rails | Fixed issues


Select option from dropdown menu and show list based on option chosen rails

Posted: 13 May 2016 07:19 AM PDT

I have a dropdown list populated with Managers in my view...

<div class= "container">   <div class="col-md-11">    <select class="form-control">     <% if current_admin.manager_approvals.blank? %>        <option>No Sub-Accounts added</option>     <% elsif current_admin.manager_approvals.all? { |ma| ma.manager_approved == false }%>        <option>No Sub-Accounts approved</option>    <% else %>        <% current_admin.manager_approvals.each do |ma| %>            <% if ma.manager_approved == true %>              <option value="<%= ma.id %>"><%= ma.manager_company %>&nbsp;|&nbsp;<%= ma.manager_phone %></option>            <% end %>        <% end %>     <% end %>    </select>  

I want it so that when the user selects a Manager from the dropdown list, my index partial will show only the items associated with that Manager.

I am unsure how to make the selection automatically query when chosen & how to display only the objects associated with that particular manager in the index list. Here is the index list as it stands now.

<tbody>      <% if #currently_chosen_manager#.reportapprovals.blank? %>      <tr>        <td width="100%">No reports available</td>      </tr>      <% elsif %>          <% #currently_chosen_manager#.reportapprovals.each do |ra| %>            <% if ra.tenant_approved == false %>                <tr>                  <td width="25%"><%= ra.tenant_last_name %></td>                  <td width="25%"><%= ra.tenant_phone %></td>                  <td width="25%"><%= ra.date_approved %></td>                  <td width="25%"><%= link_to "View Report", {:controller => "managers/reports", :action => "show", :id => ra.tenant.report || ra.report}, :method => :get, class: "btn-default btn-sm" %></td>                </tr>      <% elsif %>          <% #currently_chosen_manager#.reportapprovals.each do |ra| %>            <% if ra.tenant_approved == true && ra.tenant.confirm_info == false %>          <% end %>        <% end %>      <% else %>          <tr>            <td width="100%">No reports in progress, request a new report today!</td>          </tr>        <% end %>      <% end %>    <% end %>  </tbody>  

NameError: undefined local variable or method `u' for Gem::Source::Vendor:Class

Posted: 13 May 2016 07:17 AM PDT

I am getting the following error when trying to run

bundle install  

NameError: undefined local variable or method `u' for Gem::Source::Vendor:Class

I have been able to run this command in the past without an errors. This happens regardless of whether I add new gems or not.

Running RVM 1.9.3 on RubyMine (OSx)

Rails app is not taking facebook image after fb login

Posted: 13 May 2016 07:03 AM PDT

My rails app has fb login, when the User is authenticated through fb login then i am getting his email and full name but cant able to get his profile pic.

My Application helper,

module ApplicationHelper  def avatar_url(user)      if user.avatar          user.avatar      else              "/images/missing.png"      end  end  

end

Omniauth_callbacks_controller.rb is,

class OmniauthCallbacksController < Devise::OmniauthCallbacksController    def facebook      @user = User.from_omniauth(request.env["omniauth.auth"])            if @user.persisted?          sign_in_and_redirect @user, :event => :authentication          set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?      else          session["devise.facebook_data"] = request.env["omniauth.auth"]          redirect_to new_user_registration_url      end  end    def google_oauth2  @user = User.from_omniauth(request.env['omniauth.auth'])    if @user.persisted?    sign_in_and_redirect @user, event: :authentication    set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?  else    redirect_to root_path, flash: { error: 'Authentication failed!' }  end  

end

end

my user model is,

class User < ActiveRecord::Base  

devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:google_oauth2, :facebook]

validates :fullname, presence: true, length: {maximum: 40} has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/missing.png" validates_attachment_content_type :avatar, :content_type => /\Aimage/.*\Z/

def self.from_omniauth(auth)  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|      user.fullname = auth.info.name      user.provider = auth.provider      user.uid = auth.uid      user.email = auth.info.email      user.avatar = auth.info.avatar      user.password = Devise.friendly_token[0,20]    end  

end

I am getting the autherization from facebook but not getting fb profile pic.

How to dynamically change price charged with Stripe in Rails?

Posted: 13 May 2016 07:00 AM PDT

I am trying to integrate Stripe into my Rails app. I followed the tutorial on their website and have most of it working. My 1 question is how to dynamically change the price charged to customers.

Right now @amount is hardcoded at 500. How do I pass @price (from new.html.erb or the controller) to the 'create' action?

def new      @project = Project.find(params[:project_id])      number_of_testers = @project.testers      @price = 30 * number_of_testers  end    def create    # Amount in cents    # @amount = 500          customer = Stripe::Customer.create(      :email => params[:stripeEmail],      :source  => params[:stripeToken]    )      charge = Stripe::Charge.create(      :customer    => customer.id,      :amount      => @amount,      :description => 'Rails Stripe customer',      :currency    => 'usd'    )    rescue Stripe::CardError => e    flash[:error] = e.message    redirect_to new_charge_path  end  

new.html.erb

<center>      <%= form_tag charges_path do %>          <article>          <% if flash[:error].present? %>            <div id="error_explanation">              <p><%= flash[:error] %></p>            </div>          <% end %>          <label class="amount">            <span>Amount: $<%= @price %></span>          </label>        </article>            <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"            data-key="<%= Rails.configuration.stripe[:publishable_key] %>"            data-description="Buy usability testing credits"            data-amount="<%= @price*100 %>"            data-locale="auto"></script>      <% end %>    </center>  

Set Custom attributes for social_share_button_tag in rails 4 application

Posted: 13 May 2016 06:50 AM PDT

I have a social share page in my Rails 4 application. I am using social_share_button gem to share text, URL and image on Facebook, Twitter and Pinterest. I want to share custom text and image on these social sites. I used 'data-*' attributes inside social_share_button_tag to do this. But I am unable to share anything on Facebook, image on Twitter. I also set meta attributes for Facebook and Twitter. But I could not resolve the problem. I used social_share_button_tag like this

= social_share_button_tag(@campaign_twitter_text, 'data-twitter-title' => @campaign_twitter_text, 'data-facebook-title' => @campaign_fb_text, :url => @campaign_share_link, :image => @campaign_fb_image)  

Please help me out. Thanks!

In Rails 4, how would you log and undo all database changes specific to one user?

Posted: 13 May 2016 06:42 AM PDT

I'm trying to set a specific user account as being "sandboxed", meaning I want to roll back any database changes that user makes when their session is destroyed.

I looked at using the Paper Trail gem, but I'm not sure it can be used to roll back changes specific to one user.

Is this possible?

How to find a random item that has no rows in a join table?

Posted: 13 May 2016 07:19 AM PDT

In my Rails 4 app I have an Item model and a Flag model. Item has_many Flags. Flags belong_to Item. Flag has the attributes item_id, user_id, and reason. I need a way to find a random pending item that is not flagged. I am using enum for pending status.

I believe I can find a random pending item that is flagged with:

@pending_item = Item.pending.joins(:flags).order("RANDOM()").first  

but how can I find a random pending item that is not flagged?

"Gem::InstallError: devise requires Ruby version >= 2.1.0." when running Ruby 2.3.1

Posted: 13 May 2016 06:43 AM PDT

In my continuous integration machine I'm running Ruby 2.3.1p112:

$ ruby --version  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]  

but when I try to install gems I get an error that makes no sense:

$ bundle install --deployment  Fetching gem metadata from https://rubygems.org/  Fetching version metadata from https://rubygems.org/  Fetching dependency metadata from https://rubygems.org/  Rubygems 2.0.14.1 is not threadsafe, so your gems will be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.  Using rake 10.5.0  Using i18n 0.7.0  Using json 1.8.3  ...  Installing devise 4.0.1    Gem::InstallError: devise requires Ruby version >= 2.1.0.  An error occurred while installing devise (4.0.1), and Bundler cannot continue.  Make sure that `gem install devise -v '4.0.1'` succeeds before bundling.  

installing the gem globally works:

$ sudo gem install devise -v '4.0.1'  Successfully installed devise-4.0.1  Parsing documentation for devise-4.0.1  Done installing documentation for devise after 1 seconds  1 gem installed  

but it makes no difference. The complaint about Rubygems is also odd, as I'm running 2.6.4:

$ update_rubygems  RubyGems 2.6.4 installed  

Any ideas what might be going on?

My Gemfile looks like this:

source "https://rubygems.org"    gem "activerecord-session_store", "~> 0.1.2"  gem "bootstrap-sass", "~> 3.3.6"  gem "breadcrumbs_on_rails", "~> 2.3.1"  gem "coffee-rails", "~> 4.1.0"  gem "delayed_job_active_record", "~> 4.1.0"  gem "devise", "~> 4.0.0"  gem "devise_invitable", git: "https://github.com/scambra/devise_invitable.git" # Using master because the current release version seems not to work with Devise 4.0.  gem "font-awesome-rails", "~> 4.6.1.0"  gem "gibbon", "~> 2.2.3"  gem "haml-rails", "~> 0.9"  gem "html5shiv-rails", "~> 0.0.2"  gem "jbuilder", "~> 2.0"  gem "jquery-rails"  gem "paper_trail", "~> 4.1.0"  gem "paranoia", "~> 2.1.5"  gem "pg", "~> 0.15"  gem "pundit", "~> 1.1.0"  gem "rack-timeout", "~> 0.4.2"  gem "rails", "~> 4.2.6"  gem "redcarpet", "~> 3.3.4"  gem "respond-rails", "~> 1.0"  gem "rest-client", "~> 1.8.0"  gem "rollbar", "~> 2.11.2"  gem "sass-rails", "~> 5.0"  gem "sdoc", "~> 0.4.0", group: :doc  gem "simple_form", "~> 3.2.1"  gem "stripe", "~> 1.41.0"  gem "validation_auditor", "~> 1.0.0"  gem "uglifier", ">= 1.3.0"    group :development do    gem "quiet_assets"    gem "spring"    gem "web-console", "~> 2.0"  end    group :development, :test do    gem "annotate", "~> 2.6.5"    gem "byebug" # Call "byebug" anywhere in the code to stop execution and get a debugger console    gem "database_cleaner", "~> 1.5.3"    gem "factory_girl_rails", "~> 4.7.0"  end    group :development, :staging do    gem "mail_safe", "~> 0.3.4"  end    group :test do    gem "assert_difference", "~> 1.0.0"    gem "bundler-audit", "~> 0.5.0"    gem "capybara", "~> 2.7.0"    gem "capybara-email", "~> 2.5.0"    gem "capybara_minitest_spec", "~> 1.0.5"    gem "simplecov", "~> 0.11.2", require: false    gem "shoulda-context", "~> 1.2.1"    gem "poltergeist", "~> 1.9.0"  end    group :production, :staging do    gem "unicorn-rails", "~> 2.2.0"  end  

I'm not using RVM nor any other Ruby/Gem manager.

Installing rails on Ubuntu Bash Windows 10

Posted: 13 May 2016 06:12 AM PDT

I am using Windows 10 Insider built with Bash enabled. lsb_release shows its Ubuntu 14.04 LTS. So, I was wondering finally I can install RoR on Windows 10 and not use other installers. Because they say its Ubuntu on Windows.

I am noob at rails and I am following GoRails Guide by Chris Oliver to set RoR on Ubuntu 14.04 Win10. I tried both method using RVM & Rbenv but I ended up with errors

I also asked Chris to write a guide for this on his website and he thought it would be a great idea and but his only concern was opening up ports with Linux Software on Windows and connect to it

I am sure someone will soon find a way to install rails on Windows 10 but meanwhile I want to know if its possible or not? If yes what is it that I am doing wrong. Help me to fix it. Also what should I use for this RVM or RBENV. Which would be better in this case?

Note: Please let me know if this looks like two different questions. I will edit it. Please don't downvote because I don't even know if its possible or not. Fixing errors is the later part. Thanks

Here is rbenv error messages:

$ rbenv install 2.3.0  Downloading ruby-2.3.0.tar.bz2...  -> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2  Installing ruby-2.3.0...    BUILD FAILED (Ubuntu 14.04 using ruby-build 20160426-12-gf03f7f8)    Inspect or clean up the working tree at /tmp/ruby-build.20160513120821.313  Results logged to /tmp/ruby-build.20160513120821.313.log    Last 10 log lines:  rm -f ../../../.ext/x86_64-linux/io/wait.so  *.o  *.bak mkmf.log .*.time  rm -f Makefile extconf.h conftest.* mkmf.log  rm -f core ruby *~  rmdir --ignore-fail-on-non-empty -p  2> /dev/null || true  make[2]: Leaving directory `/tmp/ruby-build.20160513120821.313/ruby-2.3.0/ext/io/wait'  make[1]: Leaving directory `/tmp/ruby-build.20160513120821.313/ruby-2.3.0'  Generating RDoc documentation  ./ruby is not found.  Try `make' first, then `make test', please.  make: *** [rdoc] Error 1  

RVM error messages:

-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2  Installing ruby-2.3.0...    BUILD FAILED (Ubuntu 14.04 using ruby-build 20160426-12-gf03f7f8)    Inspect or clean up the working tree at /tmp/ruby-build.20160513120821.313  Results logged to /tmp/ruby-build.20160513120821.313.log    Last 10 log lines:  rm -f ../../../.ext/x86_64-linux/io/wait.so  *.o  *.bak mkmf.log .*.time  rm -f Makefile extconf.h conftest.* mkmf.log  rm -f core ruby *~  rmdir --ignore-fail-on-non-empty -p  2> /dev/null || true  cooldudeabhi@ACERASPIRE:~$ rvm install 2.3.0  ruby-2.3.0 - #removing src/ruby-2.3.0..  Searching for binary rubies, this might take some time.  Found remote file https://rubies.travis-ci.org/ubuntu/14.04/x86_64/ruby-2.3.0.ta                    r.bz2  Checking requirements for ubuntu.  Requirements installation successful.  df: Warning: cannot read table of mounted file systems: No such file or director                    y  ruby-2.3.0 - #configure  ruby-2.3.0 - #download  ruby-2.3.0 - #validate archive  cat: /dev/fd/63: No such file or directory  cat: /dev/fd/63: No such file or directory  The downloaded package for https://rubies.travis-ci.org/ubuntu/14.04/x86_64/ruby                    -2.3.0.tar.bz2,  Does not contains single 'bin/ruby' or 'ruby-2.3.0',  Only '' were found instead.  Mounting remote ruby failed with status 4, trying to compile.  df: Warning: cannot read table of mounted file systems: No such file or director                    y  Checking requirements for ubuntu.  Requirements installation successful.  grep: write error: Broken pipe  sort: fflush failed: standard output: Broken pipe  sort: write error  Installing Ruby from source to: /home/cooldudeabhi/.rvm/rubies/ruby-2.3.0, this                     may take a while depending on your cpu(s)...  ruby-2.3.0 - #downloading ruby-2.3.0, this may take a while depending on your co                    nnection...  ruby-2.3.0 - #extracting ruby-2.3.0 to /home/cooldudeabhi/.rvm/src/ruby-2.3.0..rvm install 2.3.0  

Rails: ActionController::InvalidAuthenticityToken when adding a Image

Posted: 13 May 2016 06:36 AM PDT

I am new to Ruby-on-rails and I am currently working on a project that let a user log in to add,create update delete a Marvel character. Each characters have a name, description, origin, alliance and image. I used Carrierwave for file upload.

I used the scaffold command and everything was working fine, until I decided to be able to create and update my characters on the same page using .js.erb files instead of having to redirect the user to 2 different pages for the create and the update.

I have the following error everytime I try to create a character with a image. everything works fine when I don't add a image: ActionController::InvalidAuthenticityToken

I know that there are a few different other similar questions already asked on the forum but I can't seem to find the answer to my problem.

I am using Rails 4.2.6. I tried to add the gem remotipart but it didn't fix my issue.

create.js.erb code:

$("#characters").append("<%= escape_javascript(render @character)%>");  

create action in the controller:

 def create  @character = Character.new(character_params)    respond_to do |format|    if @character.save      format.html { redirect_to @character, notice: 'Character was successfully created.' }      format.json { render :show, status: :created, location: @character }      format.js    else      format.html { render :new }      format.json { render json: @character.errors, status: :unprocessable_entity }      end  end  

end

I hope I provide enough information, thanks in advance!

Rails Html.erb syntax error

Posted: 13 May 2016 07:03 AM PDT

I cant seem to identify where the problem is. Please help me.

/home/masukami/Documents/ATPAnalyzer/app/views/atp_analyzer/admin.html.erb:205: syntax error, unexpected '{', expecting keyword_then or ';' or '\n' ...emplate: "'.freeze; if (label){;@output_buffer.append=(label... ... ^ /home/masukami/Documents/ATPAnalyzer/app/views/atp_analyzer/admin.html.erb:205: syntax error, unexpected '}', expecting keyword_end ...uffer.safe_append=': '.freeze;};@output_buffer.safe_append='... ... ^

Here's the code

var ctx = document.getElementById("dashReport").getContext("2d");  window.myLine = new Chart(ctx).Line(swirlData, {      multiTooltipTemplate: "<% if (label){%><%=label%>: <%}%> <%= value %>",      responsive: true,      scaleShowVerticalLines: false,      scaleBeginAtZero : true,  

How to call block content from HTML

Posted: 13 May 2016 06:05 AM PDT

I have this piece of code inside a .rb file:

main_content_blocks do    5.times.map do |position|      {        id:                     rand(10..100),        position:               position,        block_type:             'text',        text_markdown:          "**This is the Markdown number #{position}**",        library_image_id:       nil,        library_image_alt_text: nil,        library_image_title:    nil,        library_image_caption:  nil,      }    end  end  

From HTML, for example within a Paragraph, I need to call the different options of the main_content_blocks ... for example ID, text_markdown etc ... How do I write the HTML with ruby <% %> ?

unable to access data from rails api in angularjs

Posted: 13 May 2016 06:23 AM PDT

I am trying to create a simple todo api using rails-api gem and for frontend I am using AngularJS. When I send a get request to rails server from browser its giving the appropriate JSON response (e.g. http://localhost:3000/tasks) but when I try to access the same from angular using $http.get(http://localhost:3000/tasks) it is going to the failure handler function instead of success. What shall I do?

Here is my code

Tasks Controller

class TasksController < ApplicationController    before_action :set_task, only: [:show, :update, :destroy]      # GET /tasks    # GET /tasks.json    def index      @tasks = Task.all        render json: @tasks    end      # GET /tasks/1    # GET /tasks/1.json    def show      render json: @task    end      # POST /tasks    # POST /tasks.json    def create      @task = Task.new(task_params)        if @task.save        render json: @task, status: :created, location: @task      else        render json: @task.errors, status: :unprocessable_entity      end    end      # PATCH/PUT /tasks/1    # PATCH/PUT /tasks/1.json    def update      @task = Task.find(params[:id])        if @task.update(task_params)        head :no_content      else        render json: @task.errors, status: :unprocessable_entity      end    end      # DELETE /tasks/1    # DELETE /tasks/1.json    def destroy      @task.destroy        head :no_content    end      private        def set_task        @task = Task.find(params[:id])      end        def task_params        params.require(:task).permit(:title, :completed, :order)      end  end  

Angular code

angular  .module('app', [])  .controller('MainCtrl', [  '$scope',  '$http',  function($scope,$http){    $scope.test = 'Hello world!';      $http.get('http://localhost:3000/tasks').then(function(response){      $scope.tasks = response.data;    },function(response){      alert('error');    })  }]);  

HTML

<body ng-app="app" ng-controller="MainCtrl">      <div>        {{test}}      </div>      <ul>        <li ng-repeat="task in tasks">{{task.title}}</li>      </ul>  </body>  

When I visit the HTML page it shows error as alert

Resolve Fixnum error [on hold]

Posted: 13 May 2016 05:54 AM PDT

I take a param came of url:

authorization_selected = params[:authorization]  new_parcel = params[:new_parcel].to_i    puts authorization_selected.class (in the console show type String)  puts new_parcel.class (in the console show type Fixnum)  

So:

@portability = Portability.new  @portability.employee_id = authorization_selected.employee_id  

Return a error:

undefined method `employee_id' for 3:Fixnum  

I need that both was integer. How do it?

Darkroom.js with ruby on rails

Posted: 13 May 2016 05:07 AM PDT

I am fresher in ruby on rails. I have a problem when I install darkroom.js library on my ROR application. Its giving me following error in darkroom.js.

TypeError: document.body is null document.body.appendChild(element);

However, Its working fine when i call darkroom file directly from github.

rails text_field / text_ara empty string vs nil

Posted: 13 May 2016 06:55 AM PDT

I'm not even sure if I have a problem, but I just don't like that my text_fields and text_areas get saved in the db as empty string instead of nil.

I'm playing with the null object pattern and just realized if I create a profile but don't fill in the location field and then call <%= @user.profile.location.upcase %> then it doesn't blow up since location is a string even it it's empty.

Is this the rails convention to have it this way? If so, then why? It's weird a bit since let's say there is a number_of_pets attr on the profile and then I try to call something like

<% if user.profile.number_of_pets.odd? %>    <%= @user.profile.first_name %> has odd number of pets  <% end %>  

then it blow's up since I can't call nil.odd?.

form as usual, so it will saved as empty string if not filled

<%= form_for @profile, url: user_profile_path do |f| %>    <%= f.label :city %>    <%= f.text_field :location, class: 'form-control' %>    ......  

Access to my action edit from an other controller

Posted: 13 May 2016 05:33 AM PDT

I'm new on RoR, and I try to build a classic web app with post & user. There is a model & controller(Onlines) that allow the user to put his posts on a common wall with new informations own to this action. I'm currently trying to modify a nested form associated with this action(Onlines), by modifying the model Onlines. But I can't access to this action of my controller, and I don't understand why ?

My code ::

Onlines controller :

class OnlinesController < ApplicationController    before_action :set_online      def edit    end      private       def set_online      @post = Post.find(params[:post_id])      @online = Online.find_by(params[:id])     end     end 

Post controller :

class PostsController < ApplicationController    before_action :set_online        def show      @online.post_id = @post.id    end      private      def set_online      @onlines = Online.find_by(id: params[:id])     end     end 

Views/posts/show : `

<div class="btn-group" role="group" aria-label="...">    <%= link_to '-  taked  - ', edit_online_path(@online), data: { confirm: 'Confirmer la mise en ligne de #{@title}?' }, class: "btn btn-primary " %>  </div>

Views/onlines/edit :

<%= simple_form_for([@post, @onlines]) do |f| %>    <div class="row">              <div class="col-md-12">                <div id="Order">                  <%= f.simple_fields_for :orders do |order| %>                  <%= render 'orders_fields', f: order %>                  <%end%>                  <div class="Order_links">                    <%= link_to_add_association 'Ajouter une part', f, :orders, class: "btn btn-default" %>                  </div>                </div>              </div>            </div>    <div class="form-group text-center">  <%= f.submit "Pusher", class: 'btn btn-success' %>  </div>    <% end %>

Routes:

   Rails.application.routes.draw do    get 'profiles/show'      mount RailsAdmin::Engine => '/admin', as: 'rails_admin'        devise_for :users, :controllers => { registrations: 'registrations' }      resources :posts do   resources :comments  resources :onlines   end      get ':pseudo', to: 'profiles#show', as: :profile    get ':pseudo/edit', to: 'profiles#edit', as: :edit_profile    patch ':pseudo/edit', to: 'profiles#update', as: :update_profile    get ':post_id/online/new', to: 'online#new', as: :new_online    post ':post_id/online/:id/edit', to: 'onlines#edit', as: :edit_online        root 'posts#index'

So if you can guide me to succeed this action it would be wonderful, thanks !

mysql gem issue on bundle install

Posted: 13 May 2016 04:56 AM PDT

I have a rails app. When I do bundle install, I am getting

Make sure that gem install mysql2 -v '0.4.4' succeeds before bundling.

I am getting below error

E: Unable to locate package libmysqlclient-devgem E: Unable to locate package install E: Unable to locate package mysql2

When I do sudo apt-get install libmysqlclient-dev

I get below error.

The following packages have unmet dependencies: libmysqlclient-dev : Depends: libmysqlclient18 (= 5.5.49-0ubuntu0.14.04.1) but 10.0.25+maria-1~trusty is to be installed E: Unable to correct problems, you have held broken packages.

I am not sure what's wrong. Please help.

Integrating Bootsy with Mailboxer for the image uploads.

Posted: 13 May 2016 04:45 AM PDT

I am a ruby on rails developer and I got a task to work on the 'wysiwyg-editor', so I searched a few ways on how to use it, and found 'Bootsy'(https://github.com/volmer/bootsy) to be easiest of all which includes file uploads too.

I followed the documentation and first applied integrated it to my message model, and added the 'include Bootsy::Container' line to it to get the uploads working.

class Message < ActiveRecord::Base    include Bootsy::Container  end  

SO, I can call @message.bootsy_image_gallery.images using the object of message model.

I uploaded the images to the message model, and it worked fine for me.

Now the requirement has changed and the message model is removed and I added mailbox for the conversations insted of a simple plain message model.

Now I dont have a model to add the 'include Bootsy::Container' line, so I gone through the mailbox and found that the 'Mailboxer::Notification' model is saving the attachments. So I added, to 'Mailboxer::Notification' but for no use.

class Mailboxer::Notification < ActiveRecord::Base      include Bootsy::Container      *******************    *******************    end    

I also tried in 'Mailboxer::Message', but noavail.

class Mailboxer::Message < Mailboxer::Notification      include Bootsy::Container  end  

The Bootsy images are not getting saved to notification/message model.

If any one had tried this or have any Idea on this, please help me out.

Here is the gem reference. . Thank you in advance.

How to create card instead of table row with materialize css and rails 4 for every new entry

Posted: 13 May 2016 06:52 AM PDT

I am trying to create card instead of table row with materialize-css in rails 4 application for every new entry. But every-time I tried to create new entry it goes behind the previous one.

index.html.erb

<div class="container">  <div class="row">    <div class="s12 m6 l6 col">      <% @students.each do |student| %>        <div class="card medium hoverable">          <!-- Card Image -->          <div class="card-image waves-effect waves-light waves-block">            <%= image_tag student.avatar.url(:large), class: "activator" %>          </div>          <!-- Card Content -->          <div class="card-content">            <span class="card-title activator grey-text text-darken-4 card-modification">              <!-- Student Name -->              <%= student.Student_Prefix %> <%= student.First_Name %> <%= student.First_Name %> <%= student.First_Name %>              <i class="material-icons right">menu_vert</i>            </span><br><br>            <!-- Button -->            <p class="center-align">              <%= link_to student, :class=> "btn waves-light waves-effect grey darken-4" do %>                Show              <% end %>                <%= link_to edit_student_path(student), :class=> "btn waves-light waves-effect grey darken-4" do %>                Edit              <% end %>                <%= link_to student, method: :delete, data: { confirm: 'Are you sure?' }, :class=> "btn waves-light waves-effect grey darken-4" do %>                Delete              <% end %>              </p>          </div>          <!-- Card Reveal -->          <div class="card-reveal">            <!-- Other Details -->            <span class="card-title grey-text text-darken-4">              More Student Details              <i class="material-icons right">close</i>            </span>            <!-- Horizontal Line -->            <hr>            <!-- Card Paragraph -->            <table class="bordered centered">              <tbody>                <!-- Department And Branch -->                <tr>                  <th>Course</th>                  <td><%= student.Department_Type %> <span>in</span> <%= student.Branch %></td>                </tr>                <!-- Date of Birth -->                <tr>                  <th>D.O.B</th>                  <td><%= student.Date_Of_Birth %></td>                </tr>                <!-- Gender -->                <tr>                  <th>Gender</th>                  <td><%= student.Gender %></td>                </tr>                <!-- Class Roll Number -->                <tr>                  <th>Class Roll Number</th>                  <td><%= student.Class_Roll_Number %></td>                </tr>                <!-- University Roll Number -->                <tr>                  <th>University Roll Number</th>                  <td><%= student.University_Roll_Number %></td>                </tr>                <!-- Mobile Number -->                <tr>                  <th>Mobile Number</th>                  <td><%= student.Mobile %></td>                </tr>                <!-- Email Address -->                <tr>                  <th>Email Address</th>                  <td><%= student.Email %></td>                </tr>                <!-- Postal Code -->                <tr>                  <th>Postal Code</th>                  <td><%= student.Postal_Code %></td>                </tr>                <!-- Address -->                <tr>                  <th>Address</th>                  <td><%= student.Address %></td>                </tr>              </tbody>            </table>          </div>        <% end %>      </div>    </div>  </div>  </div>  

I want to add something like this : https://summerofcode.withgoogle.com/organizations/ for every new entry.

rails use scaffold generated api to change object's property

Posted: 13 May 2016 04:55 AM PDT

I generated with scaffold Item: rails generate scaffold item detail:integer

How do I make an ajax request that will take item that has id=n and set detail=1

Ruby rails How to search/find a specific time?

Posted: 13 May 2016 05:28 AM PDT

Hi i am working on a advance search and i want to compare requested_time to searchtime using to_i.. is there any way for me to convert requested_time: to requested_time.to_i? how?

search.rb

class Search < ActiveRecord::Base    def search_reservations      reservations = Reservation.all        reservations = reservations.where(reservation_time: searchtime) if searchtime.present?      reservations  end  end  

count distinct within haml template

Posted: 13 May 2016 04:08 AM PDT

I am wondering if there is a way to count distinct with my haml template, I have tried using group_by(&:product_id) with no success. the below code gives me a count but not unique

- @suppliers.each do |supplier|          %tr            %td.mdl-data-table__cell--non-numeric= link_to supplier.name, edit_admin_supplier_path(supplier)            %td.mdl-data-table__cell--non-numeric= supplier.variants.product.count  

Name Validation API?

Posted: 13 May 2016 04:13 AM PDT

Does anyone know of a service/API that we can use in our Rails app that will check a name to determine if it's likely real or fradulent?

So if a user enters themselves as Barack Obama, it should be fradulent. Likewise if they did something like John Doe, also so. But if they did a real name like John Reed, it would be fine.

Basically trying to up the quality of data we're getting entered when registering and I'm having trouble finding an API. One idea is maybe using the USPS address validation and trying to validate that against the entered name/address.

Heroku access remote postgresql

Posted: 13 May 2016 04:10 AM PDT

I have an heroku app and 3 different databases on 3 different servers (including localhost)

I tried to connect to each of them and i always get

PG::ConnectionBad: could not connect to server: Connection timed out  

My DATABASE_URL is correct and the app runs smoothly with heroku's native database

At first i thought it was the firewall from my hostings but i created a localhost db, opened both 5432 and 5433 ports and still heroku can't connect... i submited a ticket but no response so far.

Can someone help me?

database.yml

 development:  port: 5432  host: host  adapter: postgresql  encoding: unicode  database: database  pool: 5  username: user  password: pass     test:  port: 5432  host: host  adapter: postgresql  encoding: unicode  database: database  pool: 5  username: user  password: pass    production:  port: 5432  host: host  adapter: postgresql  encoding: unicode  database: database  pool: 5  username: user  password: pass  

How can I model the association in the following situation.?

Posted: 13 May 2016 04:29 AM PDT

I have the following association between entities in the system:

Store Vendor and User

  • store can have many vendors,
  • vendor can belong to multiple stores.
  • A user can have multiple stores, but if its a user who is related to vendor, say a person who works for that vendor, then the behavior of that user changes.

Also, for a store there can be multiple roles.

I tried polymorphic association, but since the behavior of the user changes depending on roles and whether he is a store user or a vendor user, I cannot use that.

STI can also not be used since a vast amount of columns will differ. Any ideas will be helpful.

Rails, is it a good practice to create a method without a view?

Posted: 13 May 2016 05:21 AM PDT

I am relatively new to Rails, so I still have a lot of questions. I am creating an administration panel right now.

I have a model AdminUser, a folder admin_users in my views with 2 views only, dashboard and index and an admin_users_controller which is:

class AdminUsersController < ApplicationController        def dashboard      end    def index    end    def login      if params[:admin_user][:username].present? && params[:admin_user][:password].present?        found_user = AdminUser.where(:username => params[:admin_user][:username]).first        if found_user            authorized_user = found_user.authenticate(params[:admin_user][:password])          session[:admin]=params[:admin_user][:username]        end      end      if authorized_user           redirect_to :controller => 'admin_users', :action => 'dashboard'        else          render :nothing => true, :status => :ok      end   end    end  

Although I have a method for login, I do not have a view for it, because I don't really need it.

But the fact that Rails searches for a view make me think that I am doing something wrong; or at least not doing something the Rails-y way.

Should I do something in another way? I would love to hear your suggestions.

Thank you

How to embed the iPython Notebook in a Rails application?

Posted: 13 May 2016 03:43 AM PDT

I have an iPython Notebook that needs to be embedded into my Rails application.

I have two options for doing it:

  1. Just rendering the .ipynb file on the page (like GitHub does)
  2. (desirable option) Embed the notebook with the kernel and interactive elements.

The notebook I have is quite large and it uses python-specific tricks and libraries, so rewriting it into the ruby notebook is not a good option.


So, how can one render the iPython Notebook file on the web page (like GitHub does) or how to embed the fully-functional iPython Notebook into the Rails application?

How to let rails only check current database's migration

Posted: 13 May 2016 03:28 AM PDT

I use rails 4 , and has to migrate folder under db/migrate,for example: db/migrate/A , db/migrate/B .

I have success used A migration file create A database schema , used B migration file create B database schema .

But when i connect A database , and start my rails server , it check all my migration file under db/migrate..,and show the message :

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

Anyone know how to solve this problem?

Omniauth Facebook login redirects to signup if user exists

Posted: 13 May 2016 04:29 AM PDT

I'm playing around with the omniauth-facebook gem to log into a devise session through a facebook account. When I click the "Sign in with facebook" link, everything goes well: a new account is created, I'm signed in and bounce back to the homepage with a message confirming my new session (very good!).

Problem: However when an account already exists, upon clicking the link I am redirected to the user/sign_up page. I've been following this documentation from the Devise wiki. There is a good deal of documentation on similar errors here, here, here and here. Each of the solutions, however, are already implemented in my app (as far as I can tell) OR (in the case of the last link) seem to be based on an older configuration model that seems sufficiently different from the wiki that I'm not sure it's applicable.

My best guess is that it has something to do with the callbacks controller, as @user.persisted? seems to be coming up false.This leads me to believe that my definition of @user is not correct. See below:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController    def facebook      logger.debug "Inside facebook"      # You need to implement the method below in your model (e.g. app/models/user.rb)      @user = User.from_omniauth(request.env["omniauth.auth"])      logger.debug "User is #{@user}"        if @user.persisted?        logger.debug "@user.persisted?"        debugger        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated        set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?        logger.debug "user exists"      else        session["devise.facebook_data"] = request.env["omniauth.auth"]        redirect_to new_user_registration_url      end    end      def failure      redirect_to root_path, alert: "Login failed"    end  end  

Additionally, my user model is as follows:

class User < ActiveRecord::Base      # Include default devise modules. Others available are:      # :confirmable, :lockable, :timeoutable and :omniauthable      devise :database_authenticatable, :registerable,                   :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook]        def self.from_omniauth(auth)          where(provider: auth.provider, uid: auth.uid).first_or_create do |user|              user.provider = Devise.friendly_token[0,20]              user.email = auth.info.email              user.password = Devise.friendly_token[0,20]              user.fname = auth.info.first_name              user.lname = auth.info.last_name          end      end  end  

Any suggestions would be certainly welcome! Thanks in advance.

No comments:

Post a Comment