Wednesday, April 27, 2016

List all Mongoid models in Rails console | Fixed issues

List all Mongoid models in Rails console | Fixed issues


List all Mongoid models in Rails console

Posted: 27 Apr 2016 06:52 AM PDT

I want to list all the models which have a respective collection in my mongodb database? I'm using mongoid gem for for MongoDB.

I would try something like this

ActiveRecord::Base.send :subclasses which works fine, but I'm not using ActiveRecord.

html.erb - How to fill last row with empty divs

Posted: 27 Apr 2016 06:55 AM PDT

I have a view in my rails app that is an image gallery. The view looks like this:

view.html.erb

  <div class="photo-row">      <% @item.item_images.each_with_index do |image, index| %>        <% if (index % 3 == 0) && (index != 0) %>          </div><div class="photo-row">        <% end %>                   <div class="photo-wrapper">          <a class="fancybox" rel="group" href="<%= image.picture.large.url %>"><img class="pending-photo" src="<%= image.picture.small.url %>" alt="" /></a>        </div>      <% end %>    </div>  

As you can see the row will fill up with three images and then create a new row. For my alignment I need the last non-full row to be filled with with 3 photo-wrapper divs. For example if an @item has 7 item_images I need there to be three rows. The first two are full and the last should have 1 with the image and 2 empty wrappers.

How can I achieve this?

Application.rb override base Ruby class

Posted: 27 Apr 2016 06:49 AM PDT

I have a RoR application that is doing the following in its application.rb

Digest::MD5 = Digest::SHA256  

This in turn ensures that everytime anyone invokes Digest::MD5 that it will instead replace the result with a Digest::SHA256. I believe this will have some unintended consequences, such as runtime issues that are hard to debug. Is there any alternative to this approach or is this sound?

How to get gcm registration token using gcm gem in ruby on rails?

Posted: 27 Apr 2016 06:32 AM PDT

I am trying to implement web push notifications in my rails app using gcm gem but i am not able to get the registration token provided by the user to store it into db for sending notification. Is there any solution to get the registration id?

rails ajax request returning not found but controller function exists

Posted: 27 Apr 2016 06:27 AM PDT

I've got some problems with an ajax function. I got an 500er error from server.

ajax function looks like this:

  $.ajax({      type: "POST",      url: "<%= url_for(:controller => "movies", :action => "test") %>",      data: {inputtag: tag }    })  

in my movies controller I've got this function

 # Fügt dem Video einen Tag hinzu   def test     @tag = Tag.new     if request.post?        @tag.update_attributes(params[:inputtag])        if @tag.save          redirect_to :back        else          redirect_to :back        end      end    end  

So I don't know Why I got this error

http://lvh.me/movies/test 500 (Internal Server Error)  

How can chaining one method onto another change the original method

Posted: 27 Apr 2016 06:33 AM PDT

The easiest way to explain this conundrum is with an example:

Say I have two Mongoid models which are related via a has_many relationship: A Blog post

class Post     include Mongoid::Document     field :body, type: String       has_many :comments  end  

and it's comments

class Comment     include Mongoid::Document     field :text, type: String       belongs_to :post  end  

Now I create a Post which has two comments in IRB, and I attempt to load them via the relationship. I have some DB logging enabled so I can see when the query is made:

post.comments #=>   2016-04-27 13:51:52.144 [DEBUG MONGODB | localhost:27017 | test.find | STARTED | {"find"=>"comments", "filter"=>{"post_id"=>BSON::ObjectId('571f315e5a4e491a6be39e02')}}]   2016-04-27 13:51:52.150 [DEBUG MONGODB | localhost:27017 | test.find | SUCCEEDED | 0.000492643s]   => [#<Comment _id: 571f315e5a4e491a6be39e03, text: 'great post' >, #<Comment _id: 571f315e5a4e491a6be39e12, text: 'this!' >]  

So the comments are loaded from the DB and returned as a Mongoid::Relations::Targets::Enumerable class, which looks like an array, and it contains the two comments.

Now when I open a fresh IRB console, and take a look at the criteria used to load these comments using the criteria attribute of the Mongoid::Relations::Targets::Enumerable class instance post.comments, I get this output:

post.comments.criteria #=>   => #<Mongoid::Criteria   selector: {"post_id"=>BSON::ObjectId('571f315e5a4e491a6be39e02')}   options:  {}   class:    Comment   embedded: false>  

How come no DB requests is made in this example? It's not a caching problem as I opened a new IRB console.

How can chaining criteria onto post.comments change what the .comments method does? I took a look through Mongoid's implementation of the Mongoid::Relations::Targets::Enumerable class (source on Github), but couldn't find any clues to how it works.

Rails: Searchform for Tags

Posted: 27 Apr 2016 06:47 AM PDT

I build a simple tagging system into my webapp (I've followed these steps: http://www.sitepoint.com/tagging-scratch-rails/)

So, now it's working fine that people can click on a Tag e.g. Dogs and they are going to "app.com/search/dogs".

But, now the people should also search for tags by using a form input field. At the moment I've tried this:

<%= form_tag('search', method: 'get', controller: 'static', action: 'home') do %>    <%= text_field_tag :tag, params[:tag], placeholder: "Search Posts" %>    <%= submit_tag("Search") %>  <% end %>  

That brings the user to: "app.com/search/?utf8=✓&tag=Dogs&commit=Search" and that's not working. Is there a way to achieve the other logic?

Here some (maybe) interesting code samples:

routes.rb

# search by tags  get 'search/:tag', to: 'static#home', as: "search"  

post.rb

def self.tagged_with(name)  Tag.find_by_name!(name).posts  end  

static_controller.rb

def home    if params[:tag]      @posts = Post.tagged_with(params[:tag])    else      @posts = Post.all    end  end  

posts_helper.rb

def tag_links(tags)    tags.split(",").map{|tag| link_to tag.strip, search_path(tag.strip) }.join(" ")  end  

Sorry, I'm a real beginner :) Thank you in advance!

How to lint factories immediately with guard and factory girl?

Posted: 27 Apr 2016 06:07 AM PDT

What do I need tu put in my Guardfile (in a Rails application with RSpec and FactoryGirl) to lint all my factories every time I change a factory?

I know that it is possible to run all models spec, accordingly to this question: Using guard-rspec with factory-girl-rails, but I want to only lint them all.

I tried to do this in Guardfile, but it was not enough:

watch(%r{^spec/factories/(.+)\.rb$}) {    FactoryGirl.lint  }  

Thanks in advance.

Aptana 3 - Rails debugger not doing anything

Posted: 27 Apr 2016 06:10 AM PDT

When invoking "Debug Server" nothing happens at all, no error messages, nothing. Also, nothing happens when opening a page in the browser that has breakpoints set in it.

In case i invoke "Debug as Ruby Application" i get the following exception:

Fast Debugger (ruby-debug-ide 0.6.1.beta2, debase 0.2.1, file filtering is supported) listens on 127.0.0.1:57291  Uncaught exception: uninitialized constant ApplicationController      /home/jobmob/dev/jm10/app/controllers/sessions_controller.rb:1:in `<top (required)>'      /home/jobmob/.rbenv/versions/2.3.0/bin/rdebug-ide:23:in `load'      /home/jobmob/.rbenv/versions/2.3.0/bin/rdebug-ide:23:in `<main>'  

But i think this is not the right way to debug a Rails appliation anyways, is it?

Here is my configuration:

  • Aptana Studio 3.6.1 on CentOS 7
  • Ruby 2.3.0
  • Rails 4.2.6
  • ruby-debug-ide 0.6.1 beta2

Phoenix/Elixir vs Rails - full stack benchmark? [on hold]

Posted: 27 Apr 2016 06:32 AM PDT

I'm new to Elixir/Phoenix and looking for full stack benchmarks comparisons with Rails.

I found this post (but it doesn't hit the database) http://www.littlelines.com/blog/2014/07/08/elixir-vs-ruby-showdown-phoenix-vs-rails/

A Blog index page would be fine (with variable posts list) - as long as it hits the database.

Thanks for any input!

Stop rails url_helper from requesting a lot of unnecessary objects from database

Posted: 27 Apr 2016 05:52 AM PDT

I'm creating a large xml output using rails and there are a lot of urls generated by rails. There are so called items and enclosures. Every item may have one enclosure. So I'm using has_one and belongs_to relation in my model.

I'm using

enclosure_url(item.enclosure, format: :json)  

for generating the url.

What I expect: Rails should generate the url based on the id which is stored in the items table.

What now happens is, that rails is fetching each single enclosure from the database which is slowing down my system.

Enclosure Load (2.6ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11107]]  Enclosure Load (3.1ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11108]]  Enclosure Load (0.7ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11109]]  Enclosure Load (1.5ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11110]]  Enclosure Load (6.8ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11111]]  

Is there any trick stopping rails doing this or do I have to generate my url myself?

You cannot use a Stripe token more than once

Posted: 27 Apr 2016 06:24 AM PDT

I cannot seem to charge a card then create a customer on the fly in Rails 4.

def charge   token = params[:stripeToken] # can only be used once.   begin    charge = Stripe::Charge.create(      :amount => 5000,      :currency => "gbp",      :source => token,      :description => "Example charge"    )   rescue Stripe::CardError => e    # The card has been declined   end     if current_user.stripeid == nil    customer = Stripe::Customer.create(card: token, ...)    current_user.stripeid = customer.id    current_user.save   end  end  

I have looked at this but there is no such thing as token.id as token is just a String.

Rails mailer view template pass value send by a form

Posted: 27 Apr 2016 06:34 AM PDT

Its my first attempt to use the rails mailer to send email. I however is able to send plain emails but when I tried to pass the logged in user (current_user) name and params values send by the form I am getting the error. Undefined method 'params'.

payment_mailer.rb

class PaymentMailer < ApplicationMailer      def success(user)          mail(to: "#{user.first_name} #{user.last_name} <#{user.email}>", subject: "Payment Successful")      end  end  

success.html.erb

<div class = "col-sm-12">            <h1>Payment Successful</h1>            <p>Dear <%= user.first_name %>, Thank you for being a part of our system<br>              Your invoice (#<%= params[:id] %>) has been generated.            </p>          </div>          <div class = "clearfix"></div>          <div class = "col-sm-6">            <table class = "table">              <thead>                <tr>                  <th>Paid Ammount</th>                  <th>Card Transaction Fee (2.9% + 0.30)</th>                  <th>Credited Ammount</th>                </tr>              </thead>              <tbody>                <tr>                  <td>&euro;<%= params[:amount] %></td>                  <td></td>                  <td></td>                </tr>              </tbody>              <h3>Total credited amount in your Account is: </h3>            </table>          </div>          <div class = "clearfix"></div>        </div>  

payment_controller.rb

amount = params[:amount]  @user = current_user  netamt =  (amount.to_f - ((amount.to_f*2.9)/100 + 0.30))  payment = @user.payments.create(:amount => netamt, :method => "Card", :txn_code => params[:stripeToken])  @user.update_attribute(:balance, @user.balance+netamt)  PaymentMailer.success(current_user).deliver_now  

Please guide me.

Has many through doesn't persist

Posted: 27 Apr 2016 05:27 AM PDT

I have a question about the Has Many Through relationship.

I have 3 models : Artist, Skill, and Mastery

skill.rb

class Skill < ActiveRecord::Base    has_many :masteries    has_many :artists, through: :masteries  end  

mastery.rb

class Mastery < ActiveRecord::Base    belongs_to :artist    belongs_to :skill  end  

artist.rb

class Artist < ActiveRecord::Base    has_many :masteries    has_many :skills, through: :masteries  end  

Everytime I try to attach a skill to an Artist, using artist.skills << skill, a mastery is created, but the artist_id is nil. Same thing the other way around. skill.artists << artist gives me a Mastery with a nil skill_id.

Does this mean that I have to execute both every time ? Or did I miss something ?

How TO Get the email when we seleted the person name

Posted: 27 Apr 2016 05:42 AM PDT

I need an employee email-id when I'm selecting his name, if his email id is exist in database. Can any one suggest me how to do, since I have 1400 employees and their mail id, I'm getting their names in dropdown but when I'm selecting their names I need their mail id to display in the particular field......

$("#user_employee_id").change(function(){           $.ajax({                type: "GET",                url: "/User/emailcheck",                data: { email: user.email }                  });            });    user_controller.rb  def emailcheck      @user = User.search(params[:email])    end    user.rb  def self.search(email)          if email              where('email = ?',email).first          end    end  

Can any one tell how to get the email id when I click on the employee name? I need to get email id of that employee by default in email tab.

Error while installing jwt gem in CentOS

Posted: 27 Apr 2016 05:13 AM PDT

I get the following error while trying to install jwt -

gem install jwt -v '1.5.4' ERROR: Error installing jwt: invalid gem: package metadata is missing in /home/user/.rvm/gems/ruby-2.1.6/cache/jwt-1.5.4.gem

As given in the link here, I installed postgresql, but can't locate postgre in /usr

How do I solve this error?

Amazon ruby sdk on creating an EMR cluster?

Posted: 27 Apr 2016 05:04 AM PDT

I have setup the aws sdk ruby on rails gem and i make a successful authentication. But i cannot seem to find any tutorials on creating an EMR cluster programmatically using the SDK. any tutorials you know of?

i am testing things out below

class HomeController < ApplicationController      def index      emr = Aws::EMR::Client.new      p emr.operation_names    end    end  

seem to get successfully the operations.

Writing to .zip file from binary data

Posted: 27 Apr 2016 06:48 AM PDT

I am trying to write a rails test (Using Capybara & Poltergeist) to test .zip file download functionality.

I have the binary data of a .zip file being returned from an XHR request and I am hoping to write this data into a .zip file locally and carry out further tests from there.
The following method emulates a click on a button which, when in-app, returns a zip file of all the files that have been selected:

# Perform XHR  def download_file(link)    page.execute_script("window.downloadFile = function(){ var url = window.location.protocol + '//' + window.location.host + '#{link}'; return getFile(url); }")    page.execute_script("window.getFile = function(url){ var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'blob'; xhr.send(); return xhr.response; }")      begin      file = page.evaluate_script('downloadFile()')    rescue      raise "Error during XHR. Is url valid?"    end    file  end  

I am trying to write the response to file here:

file = download_file(url)  file_path = "#{Rails.root}/tmp/files/download.zip"  File.open(file_path, 'wb'){ |f| f.write file }  

When trying to unzip the resulting file using unzip tmp/files/download.zip I'm given the following response:

Archive:  tmp/files/download.zip    caution:  zipfile comment truncated  error [tmp/files/download.zip]:  missing 3182550208 bytes in zipfile    (attempting to process anyway)  error [tmp/files/download.zip]:  start of central directory not found;    zipfile corrupt.    (please check that you have transferred or created the zipfile in the    appropriate BINARY mode and that you have compiled UnZip properly)  

I have tried overriding the MIME type to text/plain, application/zip etc. but to no avail.
Any suggestions?

How to save multiple dates in ruby

Posted: 27 Apr 2016 05:04 AM PDT

i have 2 models property and property dates. i need to save multiple start date and end date for a property in property dates tables table fields(property_id,start_date_end_date) my model tables

`class Property < ActiveRecord::Base      has_many :property_dates      accepts_nested_attributes_for :property_dates  end`

`class PropertyDate < ActiveRecord::Base  	belongs_to :property  end`
my controller

class Users::PropertiesController < ApplicationController    before_filter :authenticate_user!    before_action :set_properties, only: [:show, :edit, :update, :destroy]        def index      @properties =  Property.where(:user_id=>current_user.id)    end      def list      @properties = Property.all    end      def show      end         def new     @property= Property.new    end          def edit    end      def create      @property = Property.new(properties_params)      respond_to do |format|        if @property.save   format.json { render :index, status: :created, location: @property }        else          format.html { render :new }          format.json { render json: @property.errors, status: :unprocessable_entity }        end      end    end         def update      respond_to do |format|        if @property.update(properties_params)          format.json { render :back, status: :ok, location: @property }        else          format.json { render json: @property.errors, status: :unprocessable_entity }        end      end    end         def destroy      @property.destroy      respond_to do |format|        format.html { redirect_to  :back, notice: 'Property was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_properties        @property = Property.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def properties_params        params.require(:property).permit(:Space_name,:user_id,:address,:pincode,:image,property_dates_attributes: [ :start_date, :end_date ])

form property form i need to select multiple dates and need to save to property_dates table

my form.html.erb

 `<%= simple_nested_form_for ([:users,@property])  do |f| %>    <%= f.fields_for :property_dates do |p| %>      <%= p.text_field :start_date%>      <%= p.text_field :end_date%>    <% end %>    <% end %>`

When i write form it is not visible in my form. Why it is happening like that? Any error in my code. Please help.

Ruby on rails. Add facebook.com/ to URL if not present

Posted: 27 Apr 2016 05:29 AM PDT

my users have the option to add their website, facebook and twitter URL's to their profile.

I want to let them enter either the full URL (http://www.facebook.com/USERNAME) or part of the URL Eg. www.facebook.com/USERNAME or just USERNAME, and then have the https://facebook.com/ added automatically if needed. I want the http:// as then the entered URL will link directly to their website/facebook etc.

For the website URL I have:

before_validation :add_url_protocol    def add_url_protocol    if self.website && !url_protocol_present?      self.website = "http://#{self.website}"    end  end    def url_protocol_present?    self.website[/\Ahttp:\/\//] || self.website[/\Ahttps:\/\//]  end  

There is then further regex validation. This works fine.

The thing is I don't have much of an idea about regex and I am unsure on how to add the facebook.com/ part to this before_validation code.

Any help would be greatly appreciated, thanks.

UPDATE:

def add_url_protocol    if self.website && !url_protocol_present?      self.website = "http://#{self.website}"    end    if self.facebook && !url_facebook_present?      self.facebook = "http://facebook.com/#{self.facebook}"    end  end  

This almost works. If a user inputs USERNAME then the output is good. If the user inputs www.facebook.com/USERNAME then the ouput becomes http://facebook.com/www.facebook.com/USERNAME

Let users join multiple leagues (groups) and switch between them

Posted: 27 Apr 2016 05:13 AM PDT

I'm creating an application to store played FIFA Games and build a private leaderboard with friends.

I managed to add a user to a league (private group) but now I want to let users join multiple leagues and easily switch between them.

I've added a league_id to games and to users.

When loading the leaderboard I'm only showing the users that match current_user.league_id and for the wins and losses I'm only counting the games with that match current_user.league_id.

This works perfectly, however a user should be able to join annother league and switch easily between them. I was thinking creating another field to users that stores a collection of all joined leagues and add an action to change the active_league_id.

Can someone point me in the right direction here?

class User < ActiveRecord::Base        devise :registerable, :confirmable      devise :omniauthable, :omniauth_providers => [:facebook]        #RELATIONS SINGLE GAMES        has_many :home_games,    class_name: 'Game', foreign_key: 'home_team_user_id'      has_many :away_games, class_name: 'Game', foreign_key: 'away_team_user_id'        #RELATIONS MULTI GAMES        has_many :first_home_games,    class_name: "Multiplayergame", foreign_key: "home_team_first_user_id"      has_many :second_home_games,    class_name: "Multiplayergamer", foreign_key: "home_team_second_user_id"        has_many :first_away_games, class_name: "Multiplayergame", foreign_key: "away_team_first_user_id"      has_many :second_away_games, class_name: "Multiplayergame", foreign_key: "away_team_second_user_id"        #RELATIES SCORE CLASSEREN SINGLE GAMES         has_many :wins, class_name: 'Game', foreign_key: 'winner_id'      has_many :losses, class_name: 'Game', foreign_key: 'loser_id'        has_many :bonusses, class_name: 'Game', foreign_key: 'bonus_id'      has_many :loserbonusses, class_name: 'Game', foreign_key: 'bonus_loser_id'        has_many :firstdraws, class_name: 'Game', foreign_key: 'first_draw_id'      has_many :seconddraws, class_name: 'Game', foreign_key: 'second_draw_id'          #RELATIES SCORE CLASSEREN MULTI GAMES         has_many :firstwins, class_name: 'Multiplayergame', foreign_key: 'winner_first_id'      has_many :secondwins, class_name: 'Multiplayergame', foreign_key: 'winner_second_id'      has_many :firstlosses, class_name: 'Multiplayergame', foreign_key: 'loser_first_id'      has_many :secondlosses, class_name: 'Multiplayergame', foreign_key: 'loser_second_id'        has_many :firstbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_first_id'      has_many :secondbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_second_id'      has_many :firstloserbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_first_loser_id'      has_many :secondloserbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_second_loser_id'        has_many :firstmultidraws, class_name: 'Multiplayergame', foreign_key: 'first_multidraw_id'      has_many :secondmultidraws, class_name: 'Multiplayergame', foreign_key: 'second_multidraw_id'      has_many :thirdmultidraws, class_name: 'Multiplayergame', foreign_key: 'third_multidraw_id'      has_many :fourthmultidraws, class_name: 'Multiplayergame', foreign_key: 'fourth_multidraw_id'        belongs_to :league        has_one :league_admin, class_name: 'League', foreign_key: 'league_admin_id'    ##############################################################################################        ### TOTAL WINS CURRENT LEAGUE SINGLE PLAYER        def current_league_wins          wins.where(:league_id => self.league_id).count      end        #### TOTAL LOSSES CURRENT LEAGUE SINGLE PLAYER        def current_league_losses          losses.where(:league_id => self.league_id).count      end        #### TOTAL DRAWS CURRENT LEAGUE SINGLE PLAYER        def draws          firstdraws.where(:league_id => self.league_id).count + seconddraws.where(:league_id => self.league_id).count      end    #####################################################################################################          #### TOTAL WINS CURRENT LEAGUE MULTIPLAYER        def current_league_multi_wins          firstwins.where(:league_id => self.league_id).count + secondwins.where(:league_id => self.league_id).count      end          #### TOTAL LOSSES CURRENT LEAGUE MULTIPLAYER        def current_league_multi_losses          firstlosses.where(:league_id => self.league_id).count + secondlosses.where(:league_id => self.league_id).count      end        #### TOTAL DRAWS CURRENT LEAGUE MULTIPLAYER        def multidraws      firstmultidraws.where(:league_id => self.league_id).count + secondmultidraws.where(:league_id => self.league_id).count + thirdmultidraws.where(:league_id => self.league_id).count + fourthmultidraws.where(:league_id => self.league_id).count        end  

Controller scoreboard:

class ScoreboardController < ApplicationController      before_action :authenticate_user!        #LAAD ALLE USERS GERANSCHIKT VOLGENS SCORE        def index          @users = User.where(:league_id => current_user.league_id).sort_by(&:score).reverse            end    end  

What I need to achieve is that users can easily switch between the joined leagues and that if a user changes leagues he still appears in all the leaderboards. If a user changes league now he's not in that leaderboard any more until he rejoines, wich is normal since his league_id changes.

Rails printing array to selection_tag

Posted: 27 Apr 2016 05:22 AM PDT

I want to print an array to selection_tag

tried it this way:

 <%= f.select(:currency, {"€","$"} { |p| [p[0], p[1]] }, {}, {:class => "form-control"}) %>  

But got an synthax error...

What's my failure?

Thanks

Pundit, the record has no my model attributes

Posted: 27 Apr 2016 04:58 AM PDT

i have a model CustomerProfile, with a column i24wholesaleid In my Pundit policy CustomerProfilePolicy. i wanted to add some authorization logic to the show method so:

 def show?        if ((user.wholesale? and record.i24wholesaleid == user.customer_profile_id)) ...  

but i receive a NoMethodError:

undefined method `i24wholesaleid' for #<Class:0x007f30ce23d600>  

and i don't understand why record is a generic class, it should be an instance of my model class, isn't it? The policy is just extending the default ApplicationPolicy created by Pundit.

thanks.

Rails Omniauth - multiple social logins for same user

Posted: 27 Apr 2016 04:11 AM PDT

I've set up my Rails app to incorporate both Facebook and Twitter sign-in options and both work fine. However, when logging in for first time they create a new user rather than log in as the same user. How do I set up my app so one user can have multiple log in options - facebook, twitter or AN Other? Do I simply need to set up a seperate Authorizations/Authentications model and create an association? What other code is required?

Here's my code so far -

OmniauthCallbacks Controller -

class OmniauthCallbacksController < Devise::OmniauthCallbacksController    def all        user = User.from_omniauth(request.env["omniauth.auth"])      if user.persisted?          flash.notice = "Signed in!"          sign_in_and_redirect user       else          session["devise.user_attributes"] = user.attributes           redirect_to new_user_registration_url      end      end      alias_method :twitter, :all   alias_method :facebook, :all              end  

User model -

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: [:twitter, :facebook]         has_many :events       has_many :bookings        def self.from_omniauth(auth)      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|          user.provider = auth.provider          user.uid = auth.uid          user.username = auth.info.nickname      end  end    def self.new_with_session(params, session)      if session["devise.user_attributes"]          new(session["devise.user_attributes"], without_protection: true) do |user|              user.attributes = params              user.valid?          end      else          super      end  end    def password_required?      super && provider.blank?  end    def update_with_password(params, *options)      if encrypted_password.blank?          update_attributes(params, *options)      else          super      end  end       end  

Jquery not working in Production & Heroku but works perfectly well in development

Posted: 27 Apr 2016 04:06 AM PDT

your advise would be much appreciated.

Heroku and my production environment are not picking up my jQuery coding (Javascript files) - i have literally tried every code, suggestions and command and still unsuccessful. i have pasted my files below - if one could point out what it is i am doing wrong that needs to be corrected would much appreciate it.

-

views/layout/application.html.erb

<!DOCTYPE html>  <html lang="en">    <head>      <meta charset="utf-8" />      <meta name="viewport" content="width=device-width, initial-scale=1.0" />        <title><%= full_title(yield(:title)) %></title>        <%= stylesheet_link_tag    "application" %>      <%= javascript_include_tag "vendor/modernizr" %>        <%= csrf_meta_tags %>      <%= favicon_link_tag 'img-logo-five.png' %>      <%= favicon_link_tag 'apple-touch-icon-#{196}x#{196}.png', rel: 'apple-touch-icon', type:'image/png' %>    </head>      <body data-no-turbolink="true">      <div class="medium-12 columns container">           <% if notice %>          <div id="notice_wrapper">            <p id="notice"><%= notice %></p>          </div>        <% elsif alert %>          <div id="alert_wrapper">            <p id="alert"><%= alert %></p>           </div>        <% end %>          <%= yield %>      </div>        <%= javascript_include_tag "application" %>    </body>  </html>  

Gemfile

source 'https://rubygems.org'    gem 'rails', '4.1.10'  gem 'bcrypt', '3.1.7'  gem 'sass-rails', '~> 4.0.3'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.0.0'  gem 'jquery-rails'  gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0',          group: :doc  gem 'foundation-rails', '5.3.1.0'  gem 'simple_form'  gem "font-awesome-rails"  gem 'devise'  gem "ransack", github: "activerecord-hackery/ransack", branch: "rails-4.1"  gem "polyamorous", :github => "activerecord-hackery/polyamorous"  gem 'carrierwave'  gem 'rmagick'  gem 'acts_as_commentable'  gem "cocoon"  gem 'geocoder'  gem 'social-share-button'  gem 'twilio-ruby'  gem 'cancancan', '~> 1.10'  gem 'public_activity'  gem 'foundation-datetimepicker-rails'  gem 'jquery-ui-rails'    group :development, :test do    gem 'sqlite3',     '1.3.9'    gem 'byebug',      '3.4.0'    gem 'web-console', '2.0.0.beta3'    gem 'spring',      '1.1.3'    gem 'quiet_assets'    gem 'mailcatcher'    gem "better_errors"    gem 'awesome_print'    gem 'pry'    gem 'binding_of_caller'  end    group :test do    gem 'minitest-reporters', '1.0.5'    gem 'mini_backtrace',     '0.1.3'    gem 'guard-minitest',     '2.3.1'  end    group :production do    gem 'pg',             '0.17.1'    gem 'rails_12factor'    gem 'unicorn',        '4.8.3'  end  

config/environments/production.rb

Rails.application.configure do    config.cache_classes = true    config.eager_load = true    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true    config.serve_static_files = true    config.assets.compress = true    config.assets.js_compressor = :uglifier    config.assets.compile = true    config.assets.precompile =  ['*.js', '*.css', '*.css.erb']    config.assets.digest = true    config.log_level = :info    config.i18n.fallbacks = true    config.active_support.deprecation = :notify    config.log_formatter = ::Logger::Formatter.new    config.active_record.dump_schema_after_migration = false    config.action_mailer.default_url_options = { host: 'website.herokuapp.com' }    Rails.application.routes.default_url_options[:host] = 'website.herokuapp.com'  end  

config/locales/application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'  Bundler.require(*Rails.groups)    module RecruitmentAfricaApp    class Application < Rails::Application      config.assets.precompile += %w(*.js)      config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]      config.action_mailer.delivery_method = :smtp      config.action_mailer.smtp_settings = {         address: "smtp.mandrillapp.com", #if using a another domain this will be provided by the domain company         port: 111,         enable_starttls_auto: true,         user_name: "email@gmail.com", #this would need to be for example info@recruitmentafrica.com         password: "#####",         authentication: :login,         domain: "gmail.com",       }    end  end  

assets/javascripts/application.js

    //= require jquery  //= require jquery_ujs  //= require foundation  //= require turbolinks  //= require jquery-ui  //= require cocoon  //= require social-share-button  //= require foundation-datetimepicker  //= require_tree .      /*=========================================      general js content    =========================================*/    $(function(){ $(document).foundation(); });      // sigin-in alert message | devise signin/signout error messages  $(document).ready(function(){    setTimeout(function(){      $('#notice_wrapper').fadeOut("slow", function() {        $(this).remove();      })    }, 2500);  });    // sigin-out alert message | devise signin/signout error messages  $(document).ready(function(){    setTimeout(function(){      $('#alert_wrapper').fadeOut("slow", function() {        $(this).remove();      })    }, 2500);  });    // jquery-ui datepicker   $(document).ready(function() {    $('.datepicker').datepicker({ dateFormat: 'MM dd, yy' });     // $('.datepicker').datepicker({ dateFormat: 'D, dd M yy' });   });  

assets/stylesheets/application.css

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   *= require_tree .   *= require_self   *= require foundation_and_overrides   *= require foundation   *= require social-share-button   *= require jquery-ui   *= require font-awesome   */  

commands & codes i have tried but still no success

  • [1.] i have re-arranged my js files in application.js
  • [2.] i have set in production.rb: config.assets.compile = true
  • [3.] i have run the command: rake assets:precompile then git push heroku master
  • [4.] i have run the command: RAILS_ENV=production bundle exec rake assets:precompile
  • [5.] i have run the command: heroku run rake assets:precompile --app appName
  • [6.] my javascript does not return a 404 HTTP error online
  • [7.] i've tried adding the gem in the gemfile gem 'jquery-turbolinks' & in application.js //= require jquery.turbolinks
  • [8.] in application.rb i've added: config.assets.precompile += %w(*.js)
  • [9.] in production.rb i have added config.assets.precompile = ['*.js', '*.css', '*.css.erb']
  • [10.] i placed in a simple alert code alert('some-unique-string') pushed to heroku but do not see the alert in the console
  • [11.] i have set: assets.compress=true
  • [12.] i have set: config.assets.compress = true & run the command RAILS_ENV=production bundle exec rake assets:precompile
  • [14.] i installed the jquery.migrate.plugin i am unsure what more to do & your help would be much appreciated. Many thanks

Rails: callback in controller to change attribute from true to false in database

Posted: 27 Apr 2016 06:22 AM PDT

so I'm testing how to make a multiplayer Tic Tac Toe game, and for this I made a User model and a Game model, and by a has_many_through association they have various game_users.

Each game has an attribute: "seeking_players", that by default is true. When I create a new game_user, I check if they're exists a game with the seeking_players attribute set to true. If such a game exists, I make a new game_user for this game and I want to set this attribute to false.

But whatever I try, I can't seem to change this attribute. So, my question: what's wrong with this code: EDIT: this is the new code after suggestions from @Малъ Скрылевъ

class GamesController < ApplicationController    before_action :logged_in_user    before_action :assign_game, only: [:new]    after_action :update_seeking_players, only: [:assign_game]      def new      @game = assign_game      @game.game_users.create(user: current_user)        redirect_to game_url(id: @game.id)    end      def game    end      private      def assign_game      @game = Game.find_by_seeking_players(true) || Game.create    end      def update_seeking_players      if @game.game_users.size == 2          @game.update(seeking_players: false)      end    end    end  

PS: I also tried changing this "seeking players" attribute in the Game model (with a callback "after_add"), which is maybe a more appropriate place? But I really can't figure out how to do this...

UPDATE:

these are the Game & GameUser model

class Game < ActiveRecord::Base      has_many :game_users      has_many :users, :through => :game_users    end    class GameUser < ActiveRecord::Base      belongs_to :game      belongs_to :user      validates :game_id, presence: true      validates :user_id, presence: true    end  

UPDATE 2 the migration for seeking_players

class AddSeekingPlayersWithIndexToGames < ActiveRecord::Migration    def change      add_column :games, :seeking_players, :boolean, :default => true      add_index :games, :seeking_players    end  end  

Getting OAuthException 191

Posted: 27 Apr 2016 04:31 AM PDT

I am getting this error when logging through Facebook on a Ruby on Rails app.

What I want is when login is OK, redirect to https://hacker-news-alexvilarrubla.c9users.io/submissions but I don't exactly know how to do this.

The routes.rb code http://pastebin.com/WFgwuVNX

The omniauth.rb http://pastebin.com/QUMdLt1h

The application.html.erb http://pastebin.com/vWBJdJAQ

User.rb http://pastebin.com/Tn5wiBvv

SessionsController http://pastebin.com/Ca2PmVkv

ApplicationController http://pastebin.com/qZ6i6WGT

I guess it is something related with the Facebook App Config.

Any help will be helpful.

Thanks, Alex.

Can I use oracle_enhanced adapter in vanity gem for AB Testing?

Posted: 27 Apr 2016 03:34 AM PDT

For my production database, I am using oracle_enhanced adapter. Is this supported by vanity gem? From https://github.com/assaf/vanity, it says: "Vanity supports multiple SQL stores (like MySQL, MariaDB, Postgres, Sqlite, etc.) using ActiveRecord, which is built into Rails". I am not sure if this etc includes Oracle.

I tried using the below in my config/vanity.yml:

production:    adapter: oracle_enhanced    host: mydb.XXX.com    username: XXX    password: XXX    port: XXXX    database: mydb  

But what I get is the error message below:

Could not find oracle_enhanced in your load path (RuntimeError)  

My config/database.yml is actually using adapter: oracle_enhanced.

Any advice what I'm missing?

Is there a way do export a database in a rails app to excel

Posted: 27 Apr 2016 04:56 AM PDT

I'm being faced with a task of having a button on my rails application which basically exports the entire sqlite database to an excel file. So that the client can make pretty little graphs and do excel like things with the information.

I have done a cheeky google search trying to find a gem but I have literally 0 clue how they work and if they actually do what I want them to do.

I have tried using the Axlsx gem, but it didn't work.

I know I'm probably going to get a lot of hate on here because its not your orthodox question, but I'm at wits end with this database.

Any ideas?

Cheers

Can I allow certain views only to be rendered in iframes?

Posted: 27 Apr 2016 04:49 AM PDT

I got an application that serves widgets inside iframes of other websites. So far so good but how can I allow these widgets views only to be loaded inside an iframe and not directly?

This should work

<iframe src="http://www.example.com/widgets/example">  

But typing in http://www.example.com/widgets/example directly into a browser shouldn't be allowed.

What is or is there a best way to achieve this in rails?

No comments:

Post a Comment