dimanche 28 juin 2015

What would be the best way to fetch information of Youtube result searched by a query?

This gem yourub is not compatible with fetching particular page of the result set(pagination)

Is there any other way to fetch data sets of the Youtube result searcged by a query?

I'd like to select the page number of the result set, and the maximum number of the records to show in one query.

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Prevent foreman to crash when typo in code

I am using foreman gem on my Rails project to handle the different processes to be launched at startup (web, mailer, delayed job, ...).

It's working as expected but if I save a file with a typo or try to access a property on a nil object, foreman crash for all processes. I have to manually kill each ruby and node (for maildev) processes in order to run foreman start again.

Is there a way to prevent foreman to crash as the plumber plugin for gulp tasks ?

Thanks !

My project:

  • Rails 4.2
  • Ruby 2.2.0
  • Foreman
  • Server Unicorn
  • Mac OSX

Capybara undefined model method, not if I run the test myself

Here's my Rspec/Capybara code

visit new_user_registration_path
page.fill_in 'Email', with: 'manager@test.com'
page.fill_in 'Password (8 characters minimum)', with: 'Password'
page.fill_in 'Password confirmation', with: 'Password'
page.fill_in 'Promo code', with: "test100"
page.click_button "Sign up"

It returns this error:

1) Sign up Sign in with promo code when new user signs up with 100% promo
     Failure/Error: page.click_button "Sign up"
     NoMethodError:
       undefined method `active=' for #<Subscription:0x007f9b5f868c68>
     # ./app/models/subscription.rb:24:in `activate'
     # ./app/models/subscription.rb:17:in `setup'
     # ./app/controllers/users/registrations_controller.rb:37:in `create'
     # ./spec/integration/signup_spec.rb:18:in `block (3 levels) in <top (required)>'

However if I manually enter the info to sign up there's no error:

Here is the model code.

  def setup
    if has_full_discount?
      activate
    elsif create_stripe_customer and charge_stripe_customer
      activate
    end
  end

  def activate
    self.update_attribute(:active, true)
  end

Cancancan ability for specific case

I use cancancan gem for role based authorization rules. I need to preform something like:

can :read, Post, Post.status = 1

This means that user can read post with status = 1. How can i do that?

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

What's the correct way to reference a helper in a rails controller?

Sometimes I need to use helper methods in controllers (sanitization methods, rendering text back to the view, various other applications). What's the right way? I've got:

  • self.class.helpers.myhelper
  • view_context.myhelper
  • include MyHelper; myhelper
  • helper MyHelper; myhelper

Rails posting to a custom action on a nested polymorphic resource

I am unable to get the "like" action to work.

I am basing my action on the Raiscast no 364:

http://ift.tt/NbOPyK

I believe my problem lies with the route:

resources :polls do
  resources :likes, only: [], defaults => { :likeable => 'poll' } do
    member { post :like }
  end    
end

Has defined the following route:

like_poll_like POST   /polls/:poll_id/likes/:id/like(.:format)             likes#like {:likeable=>"poll"}

I see here that the route is looking for an id for both the poll and the like however the controller action is to create a new row for in the likes table for the poll so there is no id for the like.

My like controller is:

class LikesController < ApplicationController
  before_filter :load_likeable

  def like
    like = @likeable.likes.new(value: params[:value], user_id: current_user)
    if like.save
      redirect_to :back, notice: "Thank you for voting."
    else
      redirect_to :back, alert: "Unable to vote, perhaps you already did."
    end
  end

  private

    def like_params
      params.require(:like).permit(:value)
    end

    def load_likeable
      resource, id = request.path.split('/')[3,4]
      @likeable = resource.singularize.classify.constantize.find(id)
    end

    def likeable_id
      params[(params[:likeable].singularize + "_id").to_sym]
    end

  end

Here is the helper I am unable to get to work:

<%= link_to "Click here", polymorphic_url(poll, action: :like, value: 1), method: "post" %> to vote for <%= poll.option %>

This returns the following error:

undefined method `like_poll_url' for #<#<Class:0x007f4dbf3d4668>:0x007f4dbf308ba8>

I do not want to move the like action into the polls controller as likes is polymorphic and the same functionality will be reused.

Rails I18n :many :other :count problems

I often have problems with translations. I remember this had to do with some translations using :many, but yet when I see an error message like this

translation data {:one=>"1 month", :other=>"%{count} months"} can not be used with :count => 3

...it shouldn't make any sense, isn't :other supposed to handle all other cases ??

EDIT for the english version, I'm using the default english files, so in this particular case, this one

Is it necessary to use embedded Ruby in Rails?

I'm learning The Ruby on Rails Tutorial and currently going through the sections on embedded Ruby for the html (.html.erb) files. Is it necessary to use embedded Ruby in the html files? Are there major advantages besides code reusability? I'm trying to simply the learning process as much as I can and I'd like to skip the embedded Ruby/html parts if possible.

Concerns about using Devise with Angular

I have a Rails application that is using Devise for authentication and Angular on it's fontent to have a SPA application.

Now currently what I do is that when the user first loads the page, the user gets served a static html page with some angular on it. User can enter the credentials there and then press button to log in.

Now when the user logs in successfully then server will redirect the user back on the index page, but now I check on html page that current_user exists and then render and div that has ng-view in it. From here on every page change is done with ng-route and every request to the server is done with Angular.

Now as I understand, as long as the client making Ajax requests is under the same domain then the session cookies will be sent also along with requests. So technically the user should be checked on every request and all should be fine?

But is this a good way of handling the whole situation? Also what will happen when I later want some mobile apps to also be able to log in into that server and fetch some info form there?

Placing a bang before an instance variable - !@my_var

The logged_in? method in the code doesn't use the @ sign to reference the current_user instance variable, does this mean that the variable is local to the logged_in? method or does it still reference the @current_user variable? I noticed if I write !@current_user instead of !current_user the method doesn't work correctly. I am slightly confused how this is working under the hood because would if I had a local variable in logged_in? named current_user and I did not want it to reference the @current_user instance variable above.

def current_user
    @current_user ||= User.find_by(id: session[:user_id])
end

def logged_in?
    !current_user.nil?
end

Pass custom data while subscribing and use it while publishing to a channel - private_pub

I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.

Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.

Following js file is executed when a new message is created.

<% publish_to conversation_messages_path(@conversation.id) do %>
    $("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
    $("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);

The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?

This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.

One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.

Rails test and ActiveRecord in routes.rb

I would like to know how I could use ActiveRecord in the routes.rb file on my Rails application.

I am creating some optional modules which can be enabled or disabled dynamically. I don't want the routes to exists if the module is disabled so I created a condition around the optional routes. In development it's work properly but in the test environment, my query returns nil even if my fixtures are properly settled.

How can I make tests to use my fixtures when I am using OptionalModule.all ?

Thanks !

Here is my routes.rb file:

Rails.application.routes.draw do
  optional_modules = OptionalModule.all # this returns nil in test mode

  # by_name is a scope defined in the model
  if optional_modules.by_name('GuestBook').enabled?
    get 'toggle_guest_book_validated/:id', to: 'admin/guest_books#toggle_guest_book_validated', as: :toggle_guest_book_validated
  end
end

My fixtures:

guest_book:
  name: GuestBook
  enabled: true

My project:

  • Rails 4.2
  • Ruby 2.2.0

ruby on rails install mysql2 but not show

I know may be this is a popular problem but i try many solutions and not get to finish

I try to install mysql in rails with

gem install mysql2

And I get the result

Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.18
1 gem installed

But when i try to execute the command

bundle show mysql2

I get

Could not find gem 'mysql2'.

All these command execute in my application root directory

What is the problem ?

Rails Simple Form Country Select

I am trying to make an app with Rails and Simple Form with country_select.

I am getting an error that says:

wrong number of arguments (4 for 0)

I am using the example that i found, for simple form on the country select gem documentation page. I don't understand what's going wrong.

In my model I have:

     geocoded_by :address
  after_validation :geocode, if: ->(obj){ @obj.address.present? and @obj.address_changed? }


  def address
    [city, state, participation_country].compact.join(', ')
  end

In my form I have:

 <%= f.simple_fields_for :scope do |participants_s| %>
      <%= participants_s.simple_fields_for :participant do |par| %>
<%= par.select :participation_country,
                           priority: ["AU", "GB", "NZ", "US"],
                           selected: :participation_country,
                          label: false,
                          prompt: "Select participation country" %>

In my view I have:

<%= @project.scope.participant.address %>

Can anyone see what I have done wrong in trying to set this up? The error message indicates the problematic line is:

<%= par.select :participation_country,

I can't count 4 of anything except suggested country codes, although I deleted one of those to try and I get the same error.

CanCanCan is not blocking access for users index page

I want to stop users who aren't logged in from accessing the URL using CanCanCan

http://localhost:3000/users

My Ability model is

class Ability
include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    elsif user.roles.size > 0
      can :manage, User, :id => user.id
    else
      can :read, :all
      cannot :read, :User
    end
  end
end

And my Users controller is

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.paginate(page: params[:page],:per_page => 5)
  end

  def new
    # @user = User.new
  end

  ...
end

When I access the page as an guest user. I see the users index page instead of being redirected to login by this code in my application controller

rescue_from CanCan::AccessDenied do |exception|
  if user_signed_in?
    flash[:error] = "Access denied!"
    redirect_to root_url
  else
    flash[:error] = "Please Sign in"
    redirect_to new_user_session_path
  end
end

CanCanCan works and stops access to the other actions in the controller just not for index.

How to display error messages in a multi-model form with transaction?

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.

How should I adjust the code below so that also the error messages for user get displayed?

def new
  @organization = Organization.new
  @user = @organization.users.build
end

def create
  @organization = Organization.new(new_params.except(:users_attributes))
  #Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.

  @organization.transaction do
    if @organization.valid?
        @organization.save
        begin
          # Execute next line in debugger (with invalid user info) correctly responds with: ActiveRecord::RecordInvalid Exception: Validation failed: Email can't be blank, Email is invalid, Username can't be blank, etc.
          @organization.users.create!(users_attributes)
        rescue
          # Should I perhaps add some line here that adds the users errors to the memory?
          raise ActiveRecord::Rollback
        end
     end
  end

  if @organization.persisted?
    flash[:success] = "Yeah!"
    redirect_to root_url
  else
    @user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
    render :new
  end

end

The form view includes:

<%= form_for @organization, url: next_url do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <%= f.text_field :name %>
        # Other fields

    <%= f.fields_for :users do |p| %>
        <%= p.email_field :email %>
            # Other fields
    <% end %>

    <%= f.submit "Submit" %>
<% end %>

The error messages partial is as follows:

<% object.errors.full_messages.each do |msg| %>
  <li><%= msg.html_safe %></li>
<% end %>

Update: Following the steps from Rob below I arrived at an errors partial below. This still does not display error messages for User. I added debugger responses inside the code below and for some reason nested_model.errors.any? returns false, while the debugger inside the controller (see above) does return error messages for user.

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>

    <ul>
      <% object.errors.full_messages.each do |msg| %>
        <li><%= msg.html_safe %></li>
      <% end %>
    </ul>

  </div>
<% end %>

<% if defined?(nested_models) && nested_models.any? %>
  # Debugger: responds with "local-variable" for "defined?(nested_models)" and for "nested_models.any?" returns true.
  <div id="error_explanation">
    <ul>
      <% nested_models.each do |nested_model| %>
      # Debugger: "nested_model" has the same values as "nested_models.any?", as you would expect. But for "nested_model.errors.any?" it returns false, which it shouldn't.
        <% if nested_model.errors.any? %>    #Initially had "unless nested_model.valid?" but then errors for User are immediately displayed on loading the form page (new method).
          <ul>
            <% nested_model.errors.full_messages.each do |msg| %>
              <li><%= msg.html_safe %></li>
            <% end %>
          </ul>
        <% end %>
      <% end %>
    </ul>
  </div>
<% end %>

How to use a proc to format groupdate keys?

I'm trying to understand how the format option works in the groupdate gem.

The readme explains that format takes a string that is passed to strftime or a proc (here).

I'm having trouble understanding the proc part of this.

A simple example, if User.group_by_month(:created_at).count.keys returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] (i.e., months of the year), how would I do a simple transformation of these keys, say key * 2?

Looking at the source, format appears to be expecting a method

if options[:format].respond_to?(:call)
  options[:format]
end

So I would have expected to be able to do something like User.group_by_month(:created_at, format: 'Proc.new { |d| d * 2 }')....

But this returns only Proc.new { |d| d * 2} as a string.

What am I doing wrong?

Slim ignoring class & style on f.select field?

I'm sure I'm being blind, can you spot something I've missed:

= f.select :region, options_for_select(YAML.load_file("#{Rails.root}/config/regions.yml").collect{|x| [x[1]['name'], x[0]]}), class: "form-control", style: 'display:none;'

Slim just ignores the class & style statements, but everything else looks fine. What am I doing wrong? (rails 4).

Ruby: how to parse string '3 days ago'?

Given an input string like 3 days ago, how can I turn it into a date attribute? Maybe something like DateTime.parse('3 days ago')?

ActiveRecord::Base.establish_connection with postgresql on AWS

When got my database.yml configured like this:

default: &default
  adapter: postgresql
  encoding: utf8
  pool: 5
  timeout: 5000

production:
  <<: *default
  host: my_db_address
  port: 5432
  database: my_db_name
  username: my_db_user_name
  password: my_db_password

< test and development ommited >

When I establish connection like this:

ActiveRecord::Base.establish_connection

it says ActiveRecord::AdapterNotSpecified - 'production'

It works hovewer If I do it like this: ActiveRecord::Base.establish_connection( {:adapter => 'postgresql', :database => 'my_db_name', :host => 'my_db_address', :port => '5432', :username => 'my_db_user_name', :password => 'my_db_password'} )

I'd rather load the config from database.yml. How do I do this?

I'm on Rails 4.2.1 and Postgres 9.4

HAML/CoffeScript vs HTML/JavaScript for React on Rails

I want to use React with Rails. I already know html/JS, Begineer at Rails and just finished some tutorials on official site on React. Now I want to lear to use React with Rails. I noticed that many tutorials are using haml + coffescript. After researching on those two I found that they make developing easier and code more readable. But some people say that they generate bad html and JavaScript.

Is haml + coffescript worth learning for using them with React on Rails.

One of the reasons why I am not sure whether to use or not hamls/coffescript is that official documentation for React is written for Javascript.

how to save class as one of attribute in ROR model

so here is very small help i need for ROR , since i m a newbie in rails community. i m trying to create a model in rails named chat where i have two columns user1 and user2 , i want to store the user object in these. in grails i do this simply as

               class Chat {
                    User user1
                    User user2
                    Date chatStartedOn
                 }

and i m done , i did somewhat same for rails

        rails generate model Chat user1:User user2:User chatStartedOn:date                    

but i run db:migrate it showing me the error

            undefined method `User' for #<ActiveRecord::ConnectionAdapters::TableDefinition

my user migrate file

              class CreateUsers < ActiveRecord::Migration
                def change
                 create_table :users do |t|
                    t.string :username 
                    t.string :email
                    t.string :encrypted_password 
                    t.string :salt
                    t.timestamps
                   end
                end 
                end

Please guide how do i save users object in chat table.. help !

Why Paperclip makes a request when asked for url?

sc.image.url(:thumb)

What I see then in the logs:

[AWS S3 200 0.601484 0 retries] head_object(:bucket_name=>"****",:key=>"sc/images/000/000/526/original/file.jpg")

Why Paperclip does this request? It seems that it checks if the file still exists on the sever before giving the url, to avoid giving the broken ones.

Is there a way to stop it from doing the check so it simply returns the url without doing additional requests?

Rails how to create recursive nested_form_for for child-parent relations

Model is

class MenuItem < ActiveRecord::Base
  belongs_to :menu_item
  has_many :menu_items
  accepts_nested_attributes_for :menu_items
end

How to create a form with ability to add dynamically children and also children of children if needed (preferably with nested_form_for). In other words form shall be something like:

input
  child input
    child input (child of child)
    add/remove child (child of child of child)
  add/remove child (child)
add/remove input

Clicking add/remove will add/remove one more according child, how can I achieve this?

With Nested Resources in routes.rb with custom to_param, how can Strong Parameters allow created/update to permit?

I can't find something that'll lead in the right direction. Everyone else's similar issues with nested resources seems to resolve around accepts_nested_attributes_for… which I'm not trying to do. I'm not trying to save children from the parent, I'm trying to save directly from the child.

In my routes.rb, I have nested my resource

resources :parents, param: :parent do
  resources :children, param: :child
end

parent and child tables both have their own id column, but also have unique index on columns parent and child respectively, which I was to be used in the URL instead of the id.

http://ift.tt/1BJQ9Em

This is working fine browsing around going to the show, edit and index actions of each controller.

The problem is there are exceptions saving data.

I'm hoping the root-cause of the issue doesn't come down to a field in the child table is also called child as that's what I've used to override to_param in the model and need to keep it that way.

Navigating to the edit screen: http://ift.tt/1HoWN5u and pushing submit on the form, returns this NoMethodError exception:

NoMethodError at /parents/harry/children/sally
undefined method `permit' for "sally":String

I'm sure the problem is something to do with how my Strong Parameters line is in children_controller.rb. Can I add to require a hash of :parent and :child maybe?

def children_params
  params.require(:child).permit(:child, :date_of_birth, :nickname)
end

Update 1 (Added params): Here are the request parameters:

{
  "utf8"=>"✓", 
  "_method"=>"patch", 
  "authenticity_token"=>"fAkBvy1pboi8TvwYh8sPDJ6n2wynbHexm/MidHruYos7AqwlKO/09kvBGyWAwbe+sy7+PFAIqKwPouIaE34usg==", 
  "child"=>"sally", 
  "commit"=>"Update Child", 
  "controller"=>"children", 
  "action"=>"update", 
  "parent_parent"=>"harry"
}

Other instance variable in-scope at time of error:

@parent

<Parent id: 1, parent: "harry", description: "", user_id: 1, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

@child

<Child id: 1, child: "sally", date_of_birth: nil, parent_id: 1, nickname: nil, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

Rails Searchkick / Elasticsearch has_many and belongs_to associations

Im trying to use Searchkick to run a search and return based on multiple models.

My book model contains this

class Book < ActiveRecord::Base

  searchkick

  has_many :book_subjects
  has_many :subjects, through: :book_subjects

  belongs_to :author
  belongs_to :publisher

end

and then my controller has this

def index

 if params[:search].present?
   @books = Book.search(params[:search], operator: "or")
 else
  @books = Book.all
 end
end

I want the search results to search the associated models and return any results there too -- so the boo subject name, the author and the publisher.

thanks

How to install Ruby on Rails on Windows?

I just need to know how to install ruby and rails. I am trying to do this from two days but no result. Actually I dont have any idea about this.

samedi 27 juin 2015

Rails console NameError: uninitialized constant - nested resources

I am trying to make an app with Rails 4 and simple form.

I have three models - Project, Project_Question and Project_Answer. I made all of these by generating scaffolds so all naming conventions have been followed.

My resources are nested:

resources :projects do
    resources :project_questions do
      resources :project_answers
    end
  end

I am trying to use the console to find project answers created in my testing, but when I try to search for project answers:

2.1.1p76 :001 > Project_Answer.where(:answer => [hgvbhjb]).first

I get this error message:

LoadError: Unable to autoload constant Project_Answer, expected /app/models/project_answer.rb to define it.

The other problems on this site that seem to get the same error messages appear to be where people have not named their model.rb files in the singular. I have that.

I can only think that there is an extra step required to search the console if resources are nested. Does this sound plausible? If so, are there any materials to help figure out how to search the console with nested resources?

Can anyone see what has gone wrong?

Is there a way to limit selections in the Rails FormBuilder datetime select helper?

I want to use FormBuilder's datetime_select helper to create dropdowns for a datetime field and want to specify which minute values to use in the drop down (let's say, I want to use 0, 15, 30 and 45.)

Is there some hidden option to f.datetime_select that will let me do this?

Filter ActiveAdmin with Postgresql json column on specific json keys

I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.

I'm using active admin.

For example :

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.

It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).

One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.

I only found this but it did not work for me.

My current Active Admin Code

ActiveAdmin.register Deal do
  filter :modal_id,
  as: :select 
  collection: deal_info.all.to_a.map ???? 
end

EDIT after Andrei answer that helped move forward but not (yet) solve the problem

I added this code :

models/deal.rb

class Deal < ActiveRecord::Base
  store_accessor :deal_info, :modal_id
end

# using http://ift.tt/1LNYzLh
ransacker :modal_id do |parent|
   Arel::Nodes::InfixOperation.new('->', parent.table[:deal_info], 'modal_id')
 end

inside active admin Deal file

ActiveAdmin.register Deal do
     filter :modal_id,
     label: 'modal id',
     as: :select,
     collection: -> { Deal.all.pluck(:info_throbber).flatten.map {|el| el['modal_id'] }.uniq }

It seems to PARTLY work but not completely. Indeed it does show me on the dropdown the right various modal_id's and they are well de-duplicated BUT when I select one of them on the dropdown, and click FILTER on the right side (where the filter sidebar is), it load the whole page again WITHOUT applying the filter.

For example, on my modal_id dropdown, i have the chocie between ANY/4/5/8. If I choose modal_id 5 and click the FILTER button when the page with all the deals (that should be filtered on modal_id = 5) load, inside the sidebar modal_id select dropdown, I don't see 5 as I had chosen but ANY. The value of 5 was not "KEPT"/"REMEMBERED" and it got back to the value ANY. I don't understand why.

Web service in Rails to handle two databases

I asked in a question LINK how it was the best way to manage two databases MySQL for a Rails Web App. I searched "web services" in internet and i found a lot of things. My questions are:

1) I have to program an app in Rails, is it usefull to create the web service for this app in Rails too?

2) I have to use two databases , in my Web service how can i have to manage this?

for example, i need the list of the users of the DB1, so i write:

http://localhost:3000/users/

but how do i have to program the web service to be able to separate the two databases? I mean , if i need the users od the DB2 i would use an url like the before one:

http://localhost:3000/users/     (but for DB2)

3) I know that in a web service we should create the WSDL file. But is really necessary in my case? i will not publish the web service so , i think is not necessary to create the WSDL. is it?

Sorry for the newbie questions but it's my first time in web service programming.

Rails render partial with progress bar

I'm running Rails 4 and am trying to use a bootstrap form wizard. The thing about the form wizard is that not all of its tabs should be displayed at all times.

The form wizard is in a partial that I render via $("#tab3").html("<%= j(render partial: 'wizard' ) %>"); in update_forms.js.erb (called via an ajax call).

Everything works well in this except the progress bar doesn't display (it is 0) unless I refresh the page. Any thoughts on how I can set the progress bar when rendering the partial?

Rails 4 / Nginx - "staging database not configured"

I've never seen this error before, I don't want a staging database, but it keeps asking for it?

Message from application: 'staging' database is not configured. Available: ["default", "development", "test", "production"] (ActiveRecord::AdapterNotSpecified)

Is there a way around this?

Ordering ActiveRecord Relation by temporary column field in Rails

I need to order a query of Profile entries in an ActiveRecord::Relation object by a value that is computed on run-time.

I have created and assigned a temporary column distance in my controller for the Relation object by using attr_accessor like so:

@profiles.each do |p|
  p.class_eval do
   attr_accessor :distance
  end
end

@profiles.each do |p|
  p.distance = distance_arr[@profiles.index(p)]  # Distance values obtained from an instance array
end

However, when I try to order the Relation with the order method, I get a no such column: distance error i.e. it's not picking up the temporary field.

Here's how I tried to order it in my controller (note I'm using the will_paginate gem, but that is irrelevant).

@profiles = @profiles.order('distance ASC').paginate(page: params[:page])

create two connections MySQL on Rails project

I am creating a CRM(Customer relationship management) in Rails. I have to use two databases(MySQL).I have a doubt in the correct use of these databases.

I mean, i read on internet that is possible to open two connections in a Rails project, but is this the right way to hit the problem? is really good to open two connection in a project?

is it used?if not, what is the solution in the state of art(maybe the simpler to manage queries) for my problem?

Koala (Rails) for FQL query automatically converting GET request to POST request

I have been using Koala gem for firing FQL queries to fetch facebook data. Normally all FQL queries are GET resquests but I have seen that in facebook's Graph API explorer if the query is too long, its automatically converted to a POST request. Does the Koala gem also exhibits a similar behaviour ?

How do I render multiple lines of HTML in a helper?

I have a helper that looks like this:

if current_user.find_voted_items(vote_scope: :inspired).include?(post)
   link_to vote_inspired_post_path(post, vote_scope: :inspired), method: :post, data: { confirm: 'Are you sure this post Inspires you?' }, class: "btn btn-default" do
    "<i class='fa fa-lightbulb-o'></i> <br />Inspired".html_safe
   end
   link_to vote_happy_post_path(post, vote_scope: :happy), method: :post, data: { confirm: 'Are you sure this post makes you happy?' }, class: "btn btn-success" do
    "<i class='fa fa-smile-o'></i> <br />Happy".html_safe
   end
   link_to vote_disappointed_post_path(post, vote_scope: :disappointed), method: :post, data: { confirm: 'Are you sure this post disappointed you?' }, class: "btn btn-info" do
    "<i class='fa fa-meh-o'></i> <br />Disappointed".html_safe
   end
   link_to vote_upset_post_path(post, vote_scope: :upset), method: :post, data: { confirm: 'Are you sure this post upsets you?' }, class: "btn btn-inverse" do
    "<i class='fa fa-frown-o'></i> <br />Upset".html_safe
   end
end

I need all the links and their nested <i> tags to be rendered - but for some reason, this version is just rendering the last line.

All of that is inside a method called show_vote_buttons(post), that is being called like this in the view: <%= show_vote_buttons(@post) %>

What's the best way to tackle this?

“rails server” on existing application not working

I cloned an application, ran bundle install successfully, then tried running rails server and was met with the following error, which is basically requiring me to scaffold a rails application before using rails commands:

Usage:


 rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice
                                                         # Default: /Users/brianhedberg/.rbenv/versions/2.0.0-p481/bin/ruby
  -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)
      [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile
  -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install
  -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files
  -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files
  -S, [--skip-sprockets], [--no-skip-sprockets]          # Skip Sprockets files
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library
                                                         # Default: jquery
  -J, [--skip-javascript], [--no-skip-javascript]        # Skip JavaScript files
      [--dev], [--no-dev]                                # Setup the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                              # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit], [--no-skip-test-unit]          # Skip Test::Unit files
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory.

    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

vint-i-vuit in this post: "rails server" on existing working application not starting , but the suggested root of that problem was an issue with Rails 3, and I am on Rails 4.0.5.

Any ideas?

rails start create form url wrong

i flowed rails getting_started

in the 5.2 section “The first form”,the

http://localhost:3000/articles/new

success form

works fine before i add form “, url: create” how can i resolve this problem?

when i add url the result is:

enter image description here

and the rails run environment is:

➜ blog bin/rake routes

   Prefix Verb   URI Pattern                  Controller#Action

welcome_index GET /welcome/index(.:format) welcome#index

     root GET    /                            welcome#index

 articles GET    /articles(.:format)          articles#index

          POST   /articles(.:format)          articles#create

new_article GET /articles/new(.:format) articles#new

edit_article GET /articles/:id/edit(.:format) articles#edit

  article GET    /articles/:id(.:format)      articles#show

          PATCH  /articles/:id(.:format)      articles#update

          PUT    /articles/:id(.:format)      articles#update

          DELETE /articles/:id(.:format)      articles#destroy

➜ blog ruby -v

ruby 2.0.0p481 (2014-05-08 revision 45883) [x86_64-darwin13.1.0]

➜ blog sqlite3 --version

3.7.13 2012-07-17 17:46:21 65035912264e3acbced5a3e16793327f0a2f17bb

➜ blog rails --version

Rails 4.2.1

Raise error on unpermitted parameters rails

I am currently trying to implement raising an error when unpermitted parameters are posted in my RoR back-end. I included

  config.action_controller.action_on_unpermitted_parameters = :raise

in my development.rb configuration. Now, for example I have in one of my controllers:

def apiary_params
    params.require(:apiary).permit(:name, :municipality, :prefecture, :latitude, :longitude, :numberofbeehives, :notes)
end

If I now try posting another parameter lets say "apiary[asdf]" then an internal server error is raised correctly. However if I try posting a random "asdf" param not in the apiary hash, then the request is handled without an error. Does that mean that the random "asdf" and whatever other parameter not in the apiary is permitted? How can I fix that?

Serving images from S3 using Cloudfront

I have an S3 bucket where images are uploaded to. All of my static content is served via a Cloudfront distribution however, or at least it should be.

When I look at my page source, it indicates that all static content, except for the images in my S3 bucket, is served from Cloudfront. The images in S3 is still served from S3.

I have played around with my settings, but nothing seems to be fixing this issue.

Currently in my Cloudfront distribution I have the following settings:

  1. Origin Pointing to my web url (foo.herokuapp.com)
  2. Origin Pointing to my S3 Bucket:

    -Origin Domain name pointed to my S3 Bucket

    • Origin Path pointed to /uploads (This is the base directory in my S3 Bucket)
    • Restrict Bucket Access set to Yes
    • Tried setting Origin Access Identity to Create new and Setting Update Bucket policy to yes. I checked my Bucket Policy and it has created a Cloudfront Entry in there.

Any idea on what might cause this setup not to retrieve my S3 content via Cloudfront?

Using Hash syntax with 'OR' for Where clause in Rails

I know there are three main types of syntax's for the where clause:

  1. Pure String
  2. Array
  3. Hash

Specifying AND for the where clause is straight forward:

#Pure String syntax
@people= Person.where("name = 'Neil' AND age = 27")

#Array syntax
@people = Person.where(["name = ? AND age = ?", 'Neil', 27])

#Hash syntax
@people = Person.where({name: "Neil", age: 27})

Specifying OR for this same where clause is stumping me for the hash syntax. Is it possible?

#Pure String syntax
@people= Person.where("name = 'Neil' OR age = 27")

#Array syntax
@people = Person.where(["name = ? OR age = ?", 'Neil', 27])

#Hash syntax DOESN'T WORK
@people = Person.where({name: "Neil" OR age: 27})

How do I test fulltext fields using sunspot_matchers in rspec?

My search controller does this:

search = Sunspot.search(Item) do
  fulltext params[:q] do
    fields(:foo, :bar, :bletch)
  end
end

And in my rspec controller test I have the following:

get :show, :q => q

expect(Sunspot.session).to have_search_params(:fulltext, q, proc do
  fields(:foo, :bar, :bletch)
end)

Side note: when I tried using a block instead of a proc, the block was never executed:

have_search_params(:fulltext, q) do
  # This block was never executed
end

My support/sunspot.rb contains only the following:

Sunspot.session = SunspotMatchers::SunspotSessionSpy.new(Sunspot.session)

When I run the test, I get the following error:

  1) SearchController GET search when a user runs a search performs a fulltext search on the right fields
     Failure/Error: fields(:foo, :bar, :bletch)
     NoMethodError:
       undefined method `fields' for #<Sunspot::DSL::Search:0x007fa0f0da0168>
     # ./spec/controllers/search_controller_spec.rb:28:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/search_controller_spec.rb:27:in `block (4 levels) in <top (required)>'

What's the right way to test that my controller is supplying the correct params when doing a fulltext search? Google yields no relevant results when querying this problem.

Failure/Error: visit movie_url(movie) ActionView::Template::Error: wrong number of arguments (3 for 0..1)

This question sounds very similar to those that have already been asked and answered thought I can't seem to figure it out.

I have the following error message that makes my spec test fail.

Failures:

  1) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # ./app/views/movies/show.html.erb:24:in `_app_views_movies_show_html_erb__1138068182152565203_70152862507580'
     # ./spec/navigate_movies_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 0.20747 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

Randomized with seed 14064

My actual spec test looks like this:

require 'spec_helper'
include Rails.application.routes.url_helpers

  describe "Navigating movies" do
    it "allows navigation from the detail page to the listing page" do
    ...
    visit movie_url(movie)

    click_link "All Movies"

    expect(current_path).to eq(movies_path)
  end
end

My show page:

<article>
  <p>
     <%= link_to "All Movies", movies_path %>
  </p>
</article>

Edited:

rake routes
Prefix Verb URI Pattern           Controller#Action
movies GET  /movies(.:format)     movies#index
 movie GET  /movies/:id(.:format) movies#show

Mobile app development using ruby

[I]s there any way to develop android apps using ruby? [I]f any[,] please enlighten me on this,[ ]and please let me know the frameworks used.

root path issues when server is run as a daemon

i have several views, as well as some gems, that access the filesystem. this seems to work fine until i run the server as a daemon. rails (4.2.3)

for example in one of my views I access the README file in the root of the app

File.read('README.md')

when running as a daemon, i get the error No such file or directory @ rb_sysopen - README.md

the error page shows the Rails.root path, which is correct. i CAN fix this problem by doing:

File.read("#{Rails.root}/README.md")

however this issue breaks more than just my views. It would seem an issue with the rails server.

Rails Form_Tag Ajax Format.js ActionController::UnknownFormat

I have a form_tag for sending an email and I want to use AJAX, so that only the form could update and the rest would look the same.

contact.html.erb

<%= form_tag(site_contact_path, remote: true, class: 'response form-horizontal', authenticity_token: true) do %>
        <h2 class="contact-title">Parašykite mums</h2>
        <div class="form-group">
          <label class="control-label col-sm-4" for="name">Vardas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'name', nil, placeholder: 'Įveskite vardą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="email">El. paštas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'email', nil, placeholder: 'Įveskite el.paštą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="comment">Komentarai</label>
          <div class="col-sm-8">
            <%= text_area_tag 'comment', nil, placeholder: 'Jūsų komentaras', class: 'form-control', autocomplete: 'on', rows: '6' %>
          </div>
        </div>
        <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
        <div class="button-holder"> 
            <%= submit_tag 'Siųsti', class: 'submit' %>
        </div>
        <div class="hidden">
            <p>Ačiū! (Mes pasistenksime atsakyti Jums, kuo greičiau)</p>
        </div>
    <% end %>

routes.rb

post '/contact' => 'site#contact_send_email'

site_controller.rb

def contact_send_email
@name = params[:name]
@email = params[:email]
@comment = params[:comment]

ContactMailer.send_message(@name, @email, @comment).deliver

respond_to do |format|
    format.js
end
end

contact_send_email.js.erb

$('.form-group').hide();
$('.button-holder').hide();
$('.hidden').show();

log

 ActionController::UnknownFormat (ActionController::UnknownFormat):  app/controllers/site_controller.rb:24:in `contact_send_email'

When I press the submit button, the email is send but it seems contact_send_email action can't find contact_send_email.js.erb for some reason or doesn't understand format.js I've tried searching for similar problem on StackOverflow but the solutions didn't seem to make any effect.

grouped_collection_select and has_many, through

I'm trying to setup a form for tasks where the user selects a game and the achievements that belong to it, following Ryan Bates' tutorial. The only difference between that tutorial and what I'm working on is that I have a has_many through association in my Task model.

In the form I seem to get this error on the line for my grouped_collection_select:

undefined method 'achievement_id' for #<Task:0x007fe4da7e8cd8>

Models

class Game < ActiveRecord::Base
  has_many :achievements
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :game
  has_many :achievements, through: :game
end

class Achievement < ActiveRecord::Base
  belong_to :game
end

Tasks Form

<%= form_for(@task) do |f| %>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :game_id %><br>
    <%= f.collection_select :game_id, Game.order(:title), :id, :title, include_blank: true %>
  </div>
  <div class="field">
    <%= f.label :achievement_ids %><br>
    <%= f.grouped_collection_select :achievement_id, Achievement.order(:title), :achievement, :title, :id, :title, include_blank: true, multiple: true %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>