Wednesday, August 17, 2016

Ransack has_many through | Fixed issues

Ransack has_many through | Fixed issues


Ransack has_many through

Posted: 17 Aug 2016 07:42 AM PDT

Trying to get the right association between Shop and Products here:

shop.rb

has_many :products, through: :shoplinks  

I want to sort the shop items based on product price. The page is rendering but there is no link between the view and the controller. How can I get Shops and Products joined?

shops_controller.rb

  def show      @search = Shop.search(params[:q])      @shops = Shop.find(params[:id])      @products = @shops.products.paginate(:page => params[:page], :per_page => 20)    end  

routes.rb

 resources :shops do      collection { post :search, to: 'shops#show' }      resources :products    end  

Search view

 <%= search_form_for @search, url: search_shops_path, method: :post do |f|   <%= sort_link @search, :id, "Shop ID" %>   <%= sort_link @search, :products_newprice, "Price" %>   <% end %>  

Show view

 <% @products.each do |product| %>   <%= product.title %>   <%= product.newprice %>   <%end%>  

Stub pundit in RSpec request specs

Posted: 17 Aug 2016 07:38 AM PDT

I want to stub pundit in RSpec request specs. I have the controller action that looks like this:

  def update      user = User.find(params[:id])      authorize user        if user.update_with_password(user_params)        head :no_content      else        render json: { errors: user.errors.full_messages }, status: 422      end    end  

I have also simple spec:

require 'rails_helper'    describe 'PUT /api/users/:id' do    let(:current_user) { create(:user) }    let!(:user_1)        { create(:user) }    let!(:token)       { http_authorization_header(current_user) }      context 'when authorize is successfull' do      context 'when params are invalid' do        let(:params) do          {            user: {              first_name: nil,              last_name: nil,              password: nil,              password_confirmation: nil,              current_password: nil            }          }        end          before do          expect_any_instance_of(Api::UsersController).to receive(:authorize).with(user_1))            put api_user_path(user_1), params, token        end          it 'returns 200 http status code' do          expect(response.status).to eq 200        end      end    end  end  

This spec passes. But when I change this:

expect_any_instance_of(Api::UsersController).to receive(:authorize).with(user_1))  

to this:

expect_any_instance_of(Api::UsersController).to receive(:authorize).with(create(:user))  

which is not correct. What I'm doing wrong?

reprocess! ignores convert_options rails paperclip

Posted: 17 Aug 2016 07:36 AM PDT

I am working on already existing images and styles on s3 where I updated :convert_options for some reason. These options work flawless when new images are uploaded but however, when I call Image.last.photo.reprocess! from console for the existing model and code below, the command seems to ignore :convert_options. i say so because the Image model has an updated updated_at time but there's no conversion applied. Please let me know where I am missing out or help me a better way/script to do so. Following is the code I have:

has_attached_file :photo, :styles => {   :thumb => "50x50#",   :small => "225x257#",  :small_m => "225x257",  :small_mo => "151x173#",  :large => "350x400>",   :large_m => "350x400>",   :zoom => "800x1100"},    :convert_options => {    :thumb => "+profile -strip -quality 70 -interlace Plane -units PixelsPerInch -density 1x1",    :small => "+profile -strip -quality 70 -interlace Plane -units PixelsPerInch -density 1x1 -background white -flatten +matte -gravity center",    :small_m => "+profile -strip -quality 40 -interlace Plane -units PixelsPerInch -density 1x1 -background white -flatten +matte -gravity center",    :small_mo => "+profile -strip -quality 70 -interlace Plane -units PixelsPerInch -density 1x1 -background white -flatten +matte -gravity center",    :large => "+profile -strip -interlace Plane -units PixelsPerInch -density 1x1",    :large_m => "+profile -strip -quality 70 -interlace Plane -units PixelsPerInch -density 1x1 -background white -flatten +matte -gravity center",    :zoom => "+profile -strip -quality 70 -interlace Plane -units PixelsPerInch -density 1x1",  }  

Mailchimp Templaet Send to Mandrill option is broken for actual email

Posted: 17 Aug 2016 07:13 AM PDT

Following this article: https://robots.thoughtbot.com/how-to-send-transactional-emails-from-rails-with-mandrill

I created a drag and drop template in Mailchimp and sent it to Mandrill. Mailchimp preview and test email is good. For Mandrill, preview is good but actual email is broken, like no background color for body of email.

Creating template from scratch is not an option because I need my client to be able to take advantage of the Mailchimp drag and drop to edit templates.

thanks!

Mailer can't find template, using path to archived release folder

Posted: 17 Aug 2016 07:42 AM PDT

Only in production, action sends email which doesn't get sent citing this issue:

"Missing template general_mailer/general_email with \"mailer\" ... mail'\n/var/www/thecompany/releases/20160514000058/app/mailers/general_mailer.rb:16:in general_email

Notice the reference to the dated folder that's too old and no longer on the server.

My mailer code is this:

class GeneralMailer < ApplicationMailer    append_view_path Rails.root.join('app', 'views', 'general_mailer')      def general_email(recipient_name, recipient_email, subject, greeting, pre_link_message, link, link_label, post_link_message, closing, signature)      ...      mail(to: "#{@recipient_name} <#{@recipient_email}>", subject: @subject)       end      end  

I can assure you that in my views, the path to the file is views/general_mailer/general_email.html.erb

Can someone help me get the mailer to look in the "current" folder instead please?

How to put multiple form_for's on the same page

Posted: 17 Aug 2016 07:12 AM PDT

Oke guys i'm busy making an invoice app and i'm kinda stuck atm.

On the invoice page i have something similar like

<%= form_for(@invoice) do |f| %>   <%= f.date_select :date %>        <%= form_for :customer do |c| %>      <%= c.text_field :company_name %>      <% end %>     <%= f.text_field :invoice_number %>  <% end %>  

But when i save the invoice and try to edit it again the customer details are gone.

How do you put multiple form_for's in one page and save them all with one submit button?

Seed acts-as-taggable-on with tags set to different categories

Posted: 17 Aug 2016 07:03 AM PDT

Im trying to figure out how I can prepopulate my tag list for the different categories. I have two tag list that I use (cuisine_list, technique_list) and have a list of items I would like to prepopulate my tags with so that there is some suggestions in the autocomplete for them. I know I can use the seed file to do something like this:

list = ['tag 1', 'tag 2', ...]    list.each do |tag|    ActsAsTaggableOn::Tag.new(:name => tag).save  end  

But that doesnt create the association with the specific tag_list. How can I add them to the cuisine_list or technique_list?

Rails: How to upload your Heroku PG database to your local (SQLite) development environment?

Posted: 17 Aug 2016 06:46 AM PDT

I am a rails newbie and have a production app that is deployed with Heroku. I would like to upload my production database (PG) to my local development environment (SQLite). I am sure this is straightforward but I want a SAFE method to do this (i.e. without any risk of damaging my production data).

Using the Acts_as_votable gem with Angularjs

Posted: 17 Aug 2016 07:45 AM PDT

Basically I want to access Acts_as_Votable through an Angular template. I have a list of cars that people can vote on. However, I can't display the votes when the list is rendered in Angular.

I'm guessing I need to pass some sort of association for :votes when the json gets rendered in the controller, like with :marque. This is where I've got to so far. Can't for the life of me work it out and resorted to actually asking a question rather!

Cheers

cars_controller.rb

def index    @cars = Car.all    respond_to do |format|      format.html {}      format.json {render json: @cars, :include => :marque}    end  end  

index.html.erb

<div ng-repeat="car in cars | rangeFilter:slide | filter:name">    <div class="col-sm-6 col-md-4">       <ul class="thumbnail">          <li>{{car.marque.name}}</li>          <li>{{car.name}}</li>          <li>{{car.power}}</li>          <li>{{car.rotor}}</li>          <li>Votes: {{car.votes_for.size}} </li>          <li><%= link_to 'Show', URI::unescape(turbine_path('{{car.id}}'))%></li>          <li><%= link_to "up", URI::unescape(like_turbine_path('{{car.id}}')), method: :put, class: "btn btn-default btn-sm" %></li>        </ul>      </div>   </div>  

Copy file to new folder with FileUtils

Posted: 17 Aug 2016 06:17 AM PDT

I'm developing a RoR app and want to move a file 'flower.png' from /public folder to /public/images folder which currently doesn't exist in a migration. I found out that I can do that with the help of FileUtils module.

My migration:

class MoveFileToImagesFolder < ActiveRecord::Migration    def change      FileUtils::mkdir_p 'public/images'      FileUtils.cp('public/flower.png', 'public/images/')    end  end  

Do I need to require 'fileutils' in the migration or it will work fine like this?

Capybara look through whole page

Posted: 17 Aug 2016 06:16 AM PDT

How to set up capybara to search through whole page?

i have button which located almost in the end of page,so need to scroll down to see it,and capybara can't find it.

find('a.to_blog_root', text: 'Main page').click  

I use selenium driver

Render result for a Form rails / gem geocoder

Posted: 17 Aug 2016 06:59 AM PDT

I would like to render the result of my form when users are clicking on the "Search" button.


I think I am missing something with the Model (i dont really know if i have to add something on my user model) or the Html.

I have a controller : Searchscontroller

class SearchsController < ApplicationController    def index      if params[:city].present?        @searchs = User.near(params[:city], params[:distance] || 10, order: :distance)      else        @searchs = User.all      end    end  

and a form in search.html.erb

<%= form_tag search_path, method: :get do %>    <%= label :user, "Search User near : " %>    <%= text_field_tag :city, params[:city] %>      <%= label :distance, "Distance : " %>    <%= text_field_tag :distance, params[:distance] %>      <%= submit_tag "Search" %>  <% end %>      #NOT SURE WITH THAT PART, I think its not working, just the %else is displayed#      <div>      <% if @searchs.present? %>        <%= render @searchs %> # it might be @users instead ? #      <% else %>        <p>Oops no user around <%= params[:city] %>.</p>      <% end %>      </div>  

My users have been located with the gem geocoder, that part is fine, I got Lat and Longitude (and the city in DB, its working in the console User.Near('City') ), but I just would like to display a list of result , like this when I click on the form :

Around London / distance 10 km => >Search<
Result
> @user 1
> @user 2

I hope someone got the answer for me, many thanks in advance

Route.rb

Rails.application.routes.draw do   devise_for :users   resources :users, only: [:index, :show]   root "pages#home"   get "search" => "pages#search"  

ActiveRecord Connection Adapter return value

Posted: 17 Aug 2016 07:25 AM PDT

I had a bit more complex sql-query which i decided to use plain sql rather than writing it with AR. I wrapped the sql-statement inside ActiveRecord::Base.connection.exec_query` .

The method basically looks like that:

def sc_agent    return ActiveRecord::Base.connection.exec_query("SQL").as_json  end  

The serializer as_json gives me a json hash with json strings. So also id's are now strings

{"id":"123","age":"99"}  

On standard queries where i use AR i receive nicely formatted json with the correct types.

How can i retain the correct types of all the values when using the ConnectionAdapter directly? Thanks for everything!

I want to get TAX/VAT by marketplaces from Amazon API via gem peddler. How can I get tax/vat values?

Posted: 17 Aug 2016 05:48 AM PDT

client = MWS::Orders::Client.new(      primary_marketplace_id: 'xxxxxxxxx',      merchant_id: 'xxxxxxxxxx',      aws_access_key_id: 'xxxxxxxxx',      aws_secret_access_key: 'xxxxxxxxxx',      auth_token: 'xxxxxxxxx'  )    list_order_items = client.list_order_items('111-111111111-111').parse    puts '!!!!!!!!'  puts list_order_items  puts '!!!!!!!!'  

rails runner test.rb

I want to get TAX/VAT by marketplaces from Amazon API via gem peddler. How can I get tax/vat values?

Paper_trail and Rails_admin undefined 'version_class_name'

Posted: 17 Aug 2016 05:45 AM PDT

When I try to add history to my admin I get the following error:

undefined method 'version_class_name' for #<Class:0x0056249a09f190>  

I have the two gems install (remotipart and rails_admin >= 1.0.0.rc) and in my rails_admin.rb file I put in this:

RailsAdmin.config do |config|      ### Popular gems integration      ## == Devise ==    config.authenticate_with do      warden.authenticate! scope: :user    end    config.current_user_method(&:current_user)      ## == Cancan ==    # config.authorize_with :cancan      ## == Pundit ==    # config.authorize_with :pundit      ## == PaperTrail ==    config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0      ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration      ## == Gravatar integration ==    ## To disable Gravatar integration in Navigation Bar set to false    # config.show_gravatar true      config.actions do      dashboard                     # mandatory      index                         # mandatory      new      export      bulk_delete      show      edit      delete      show_in_app        ## With an audit adapter, you can add:      history_index      history_show    end  end  

Ive tested the paper_trail versions in the console and everything works fine. I have added the object_changes column per the instructions also.

jquery.turbolinks not working on $(document).ready in Rails

Posted: 17 Aug 2016 06:09 AM PDT

After realising my rails app was experiencing the well known issue of $(document).ready) not working with turbolinks I installed jquery.turbolinks exactly as the docs suggest but I'm still experiencing the same issue. Whenever turbolinks are used to navigate none of the JavaScript in my $(document).ready) function works.

Here is some of my code:

In application.js:

//= require jquery  //= require jquery.turbolinks  //= require jquery_ujs  //= require_tree .  //= require turbolinks  

Example of JavaScript not working:

$(document).ready(function() {    $('.notice:empty').hide();    $('.alert:empty').hide();    $(".notice").delay(2000).fadeOut();    $(".alert").delay(2000).fadeOut();  });  

Why I get CSRF warning in my application?

Posted: 17 Aug 2016 05:39 AM PDT

I find a very interesting bug in my app: when user with bad internet connection open a page and while this page is loading, user click on the modal window with form - he get an error

ActionController::InvalidCrossOriginRequest - Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.  

why user get this error? it is bug or feature?

Is it bad to group together like tests into a single test?

Posted: 17 Aug 2016 07:22 AM PDT

My team is using Cucumber / Ruby on Rails. We have some scenarios such as the following:

Scenario: Create a Data Set  Scenario: Update a Data Set  Scenario: Invalid Data Set - Invalid Name  Scenario: Invalid Data Set - Missing Source  Scenario: Invalid Data Set - Invalid Rate  ...  

A co-worker is asking that I group together all of the invalid tests into a single scenario. His reasoning is because when we sit with our Quality team, we have to read all of the scenarios aloud, and it would save time by only reading one instead of many.

Scenario: Create a Data Set  Scenario: Update a Data Set  Scenario: Invalid Data Set    # Steps for invalid name    # Steps for missing source    # Steps for invalid rate  

I don't think I can agree with this because I feel that tests should be completely isolated. If I want to add a new invalid scenario, then I would have to run more code than I need to if they were grouped together. I wanted to know if anyone had a more official answer.

Is it bad to group together like tests into a single test?

How to make beta test evironment from prod in rails?

Posted: 17 Aug 2016 06:07 AM PDT

I have a rails application which is having a bunch of tables in its schema. The database is stored on a different machine. And I can handle all the queries like update/search from MySQLWorkBench

I updated one of the table by adding two columns in it from MySQLWorkBench not by running any rails command.

So, is there anything else that I need to do so that my schema.rb is changed or it'll change automatically?

In case I am supposed to run a command to let the changes reflect in schema.rb please guide me at what directory I'll run it and on which machine (My developer desktop or the machine on which database is stored).

Rails Upvote Routing Error

Posted: 17 Aug 2016 05:43 AM PDT

I'm getting an error, and have tried debugging it but with no avail.

I've just added a 'like' button to my site that allows users to like a document. I have put the code below in the show.html.erb file and it works fine, although when I move it to the index.html.erb file, I get this error:

No route matches {:action=>"upvote", :controller=>"documents", :id=>nil} missing required keys: [:id]

This is the like button code:

<%= link_to like_document_path(@document), method: :put, class: "like-image" do %>      <p class="like-document-count">          <%= @document.get_upvotes.size %>      </p>  <% end %>  

This is the relevant code for my documents controller:

def index      if params[:category].blank?          @documents = Document.all.order("created_at DESC")            if params[:search]          @documents = Document.search(params[:search]).order("created_at DESC")          elsif          @documents = Document.all.order("created_at DESC")          end        else          @category_id = Category.find_by(name: params[:category]).id          @documents = Document.where(category_id: @category_id).order("created_at DESC")      end  end    def upvote      @document.upvote_by current_user      redirect_to :back  end    private    def find_document      @document = Document.find(params[:id])  end  

This is my routes.rb file:

Rails.application.routes.draw do    devise_for :users      resources :documents do          member do              put "like", to: "documents#upvote"          end      end        root 'documents#home'        get '/englishstandard', to: 'documents#englishstandard'      get '/englishadvanced', to: 'documents#englishadvanced'      get '/physics', to: 'documents#physics'      get '/chemistry', to: 'documents#chemistry'      get '/biology', to: 'documents#biology'      get '/economics', to: 'documents#economics'      get '/business', to: 'documents#business'      get '/modern', to: 'documents#modern'      get '/ancient', to: 'documents#ancient'      get '/geography', to: 'documents#geography'  end  

I'm not sure what I'm doing wrong? How come the code works while in the show.html.erb file, but not while in the index.html.erb file?

I'm using the acts_as_votable gem by the way.

Huge number of rows in pivot table (Postgresql)

Posted: 17 Aug 2016 06:08 AM PDT

I have a database of videos. Each video can have multiple categories, so I have pivot table to connect category and video together.

The problem is that the video_category pivot table has 4769325 rows, which I think is huge for such a simple thing.

Is there better way how to store the relation between video and category and still be able to query through them? It's a RoR app with Postgresql DB.

What is the best way to duplicate a row in Ruby on Rails

Posted: 17 Aug 2016 05:21 AM PDT

I have a list of data and I'd like to duplicate a row when an user click on the copy button. Example: This is the current list:

enter image description here

If an user click on user 02 copy button, this row should duplicate (and persist on database) like that:

enter image description here

What is the best way to do this?

I hope that I was clear.

Tks in advance

Import html to rails method (in helper.rb)

Posted: 17 Aug 2016 05:14 AM PDT

I need piece of code for couple of times, and to follow DRY method (don't repeat yourself) i want to escape using this piece and retyping it for 5 times or more. So I want to define method what will contain both ruby and html, and ruby in html and js to, code. But I have problems with realization.

My html.erb look like this:

<% div_count = 1 %>  <div>    <% for post in @posts %>      <div class="post-on-main-page-<%= div_count %>"           id="js-count-<%= div_count_for_js %>">        <script>          $("#js-count-<%= div_count_for_js %>").click(function(){            window.location.href = "<%= post_url(post) %>";          });        </script>      <%= image_tag(post.picture.url) %>      <span><h5><%= post.theme %></h5></span>    </div>    <% end %>  <% div_count += 1 %>  <% if div_count == 4 %>    <% div_count = 1 %>  <% end %>  </div>  

And I want create method, I think in application_helper.rb will do with this piece of code. What will look something like that:

def method_name(parameter)  <% div_count = 1 %>      <div>        <% for post in parameter %>          <div class="post-on-main-page-<%= div_count %>"               id="js-count-<%= div_count_for_js %>">            <script>              $("#js-count-<%= div_count_for_js %>").click(function(){                window.location.href = "<%= post_url(post) %>";              });            </script>            <%= image_tag(post.picture.url) %>            <span><h5><%= post.theme %></h5></span>          </div>        <% end %>      <% div_count += 1 %>      <% if div_count == 4 %>        <% div_count = 1 %>      <% end %>    </div>  end  

The result what I want for html.erb

<%= method_name(@posts)%>  

How can I make this to work?

Autosaving record on multiple unsaved belongs_to relationships

Posted: 17 Aug 2016 05:22 AM PDT

Given a three-model setup like this in Rails 5 (so the belongs_to are all not optional):

class LineItem < ApplicationRecord    belongs_to :order # in the migration: t.references :order, null: false    belongs_to :parcel # in the migration: t.references :parcel, null: false  end    class Order < ApplicationRecord    has_many :line_items    has_many :parcels  end    class Parcel < ApplicationRecord    belongs_to :order    has_many :line_items  end  

the following test fails:

class AutosaveAllTest < ActiveSupport::TestCase    def test_with_autosave      order = Order.new()      order.line_items.build()      order.parcels.build(line_items: order.line_items)      order.save!      assert(order.parcels.count == 1)      assert(order.line_items.count == 1)      assert(parcel.line_items.count == 1)    end  end  

order.save! raises an SQL error:

ActiveRecord::StatementInvalid: NOT NULL constraint failed:   parcels.order_id: INSERT INTO "parcels" ("created_at", "updated_at") VALUES (?, ?)  

Is this a bug or am I doing things very wrongly? I'm currently working around this problem, and have also considered a has_many :through relation to solve it, but in a perfect world I would love to have the above working.

pg_search multisearch sort by attributes of searchable

Posted: 17 Aug 2016 04:58 AM PDT

I have a rails app in which I am trying to implement pg_search.
The app has a story model and a comment model and I am trying to have a search page where user can search across both.
Both models have a points integer value, I want the user to be able to sort the results on points, or created_at.
The issue is multisearch returns a PgSearch::Document objects list, not the actual records.This dosen't have points or created_at property to sort on, it simply has polymorphic association to the model as searchable property.
Also it seems order dosen't work on PgSearch query and we need to use reorder.
How do I enable sorting the pgsearch::documents results on attributes of associated searchable object ?

Linking many existing models to one new one. Ruby on Rails

Posted: 17 Aug 2016 05:45 AM PDT

So I am making an app that reviews books, articles and the like.

I have created the backbone of the app by creating models, views, controllers etc for Piece(the book or article), Section(self explanatory), Subsection, and Subsubsection.

I want to add a new model into the mix, a "Links" model (which will just be a link to another source or website). My issue is that I don't know how to make ALL of my previously stated models have "Links". I want each of The above models to have access and CRUD capabilities to their "Links", but so far all i have read about is has_many or has_and_belongs_to_many.

As far as I understand, those kinds of relations only relate ONE model to ONE other model, even if Piece might have many Sections, it only relates these two models.

I guess the Links model would have to have an obligatory piece_id, but then optional id's such as: section_id, subsection_id depending on where the link was. So if in Chapter 3 of my first book i want to add a link, it would have an obligatory piece_id=1 and then a section_id=3, but then no subsection_id or subsubsection_id.

So how do I go about creating a model such that it belongs to several other models? Or is this even possible?

https://github.com/kingdavidek/StuddyBuddy

ActiveAdmin sortable_handle_column sort with scope

Posted: 17 Aug 2016 04:43 AM PDT

I am using "activeadmin-sortable" gem for drag & drop sorting in active admin. Everything works fine, but what is my problem is, I need to use a scope for this page. For example, I have Event Model and Event Categories Model. Here, Event -> has_many -> EventCategories. I have applied sorting for Event Categories model. When I drag & drop any record, it will go to the 'sort' method with the params position & id and then it will automatically calculate and re-order the positions based on the dropped position. Here, the resultant data will be for the whole event categories model, not for specific event's categories.

I want to apply an event scope for this calculation. I tried with the 'super' class like we override other active admin methods, but it shows error as 'superclass' is not available for 'sort' method.

I want to apply this re-ordering only for the event's categories, not the whole event categories table. because, this table will contain same values belong to various events.

Can't sign_in user with twitter account, devise omniauth

Posted: 17 Aug 2016 04:40 AM PDT

I am making plugin for engine which will enable omniauth login via twitter or facebook. When i try to sign in user with twitter account i get message:

Could not authenticate you from Twitter because "Invalid credentials".

What can cause this issue?

I got following:

my_engine_model_extenders.rb

Rails.application.config.to_prepare do    MyEngine::User.class_eval do        devise :omniauthable, :omniauth_providers => [:facebook, :twitter]        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.email = auth.info.email          user.password = Devise.friendly_token[0,20]        end      end      end  end  

config/initializers/devise.rb

Devise.setup do |config|            config.omniauth            :facebook,Rails.application.secrets[:fb_id],Rails.application.secrets[:fb_secret]            config.omniauth :twitter, Rails.application.secrets[:tw_id],    Rails.application.secrets[:tw_secret]      end  

callbacks_controller.rb

class CallbacksController < Devise::OmniauthCallbacksController      def facebook        @user = User.from_omniauth(request.env["omniauth.auth"])        sign_in_and_redirect @user    end      def twitter        @user = User.from_omniauth(request.env["omniauth.auth"])        sign_in_and_redirect @user    end  end  

routes.rb

MyEngine::Core::Engine.add_routes do    devise_scope :user do      match '/auth/:provider/callback', to: '/devise/sessions#create', via: [:get, :post]      match '/logout', to: '/devise/sessions#destroy', via: [:get, :post]    end  end  MyEngine::Core::Engine.draw_routes  

input a javascript string to ruby asset_path

Posted: 17 Aug 2016 04:30 AM PDT

I am trying to call an asset_path on a javascript variable, but it doesn't seem to work. My code looks like this:

function loadBVH(filename){      load("<%= asset_path '" + filename + "' %>");  }  

filename is simply a string that the methode gets.

if i call the mothod like the following it does work:

load("<%= asset_path 'teddy.bvh' %>");  

show custom records in activeadmin index page

Posted: 17 Aug 2016 04:24 AM PDT

I want to show venues in a conditional approach on index page in activeadmin like if a current_admin_user role would be super_admin then he can view all records, if current_admin_user role would be city_manager then he can also view all records but if current_admin_user role would be venue_manager then he can only view there venues.

I am not able to do this, I have venues as per conditional approach but let me know how to use venues variable to list out venues on index page

index do       if current_admin_user.is_super_admin?          venues = Venue.all      elsif current_admin_user.is_city_manager?          venues = Venue.all      elsif current_admin_user.is_venue_manager?            venues = current_admin_user.user.venues      else          venues = Venue.all      end      selectable_column      id_column      column :title          actions  end  

Thanks In Advance.

No comments:

Post a Comment