samedi 25 avril 2015

Rails 4 + Solr: Show search result from different model


I have search method in my controller:

def search
  @search = Sunspot.search [Post, Siri] do
    fulltext params[:q]
  end
  @posts = @search.results
end

Then i have this in my view:

- @posts.each do |p|
  %h5= p.title

My question is how to show separately in view if @posts from Post model & if @posts from Siri model.

The reason that i want it seperately is because there is some attr are not exists in Post model but exists in Siri model.

Thanks in advance!


Rails 4.2 / PostgreSQL and Test Database Preparation


We are using Rake::Task['db:create'].enhance to add a new schema and create an extension in the newly created schema as below.

Rake::Task['db:create'].enhance do
  ActiveRecord::Base.connection.execute('CREATE SCHEMA IF NOT EXISTS shared_extensions;')
  ActiveRecord::Base.connection.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA shared_extensions;')
end

Can we enhance the test database preparation in the same way?


Join the associated object into the belongs_to object


I have an Event model which has many DateEntry because an event can have multiple datetimes.

I have a view where I see all the events with date entries for a specific day. For which I've made this class method in models/event.rb:

def self.by_date(date)
  includes(:date_entries)
  .where(date_entries: { begins_at: date.beginning_of_day..date.end_of_day })
end

And it works fine.

Now on the view I loop over the events I grabbed with that query:

@events.each do |event|
  # whatever

I am looking for a way to use the date from the selected DateEntry in the loop. I think I have to use ActiveRecords joins method, but I have tried in many ways and when I am not getting an error the output is still the same.

For clarifying, I want to do in the loop something like event.selected_date_entry_by_the_by_date_method.begins_at or something like that.


has_many through roles and scopes on the third model


Lets say I have movies, people and movies_people

class Person < ActiveRecord::Base
  has_many :movies_people
  has_many :movies, through: :movies_people

class Movies < ActiveRecord::Base
  has_many :movies_people
  has_many :people, through: :movies_people


class MoviesPerson < ActiveRecord::Base
  belongs_to :movie
  belongs_to :person
end

The table movies_people has a role attribute, where I want to store the person's job in the movie. Right now I can do things like this in the console:

u = User.first
m = Movie.first
m.people << u

then find the right movies_people entry and set 'role'

retrieving looks like this:

m.people.where(movies_people: {role: :actor})


Whats the best way to:

  1. Save the role (to the third table) when joining people to movies?
  2. Return all the actors in a movie vs. all the directors vs. all the writers?

Favouriting a picture in a Rails app


I am trying to figure out how to execute a "favourite a picture" method in a Rails app, which I am very new to, going from a JS/Meteor background.

The point is I have a User, FavPic, Pic classes:

class User < ActiveRecord::Base
  #some user oauth stuff would be here

  has_many :fav_pics
  has_many :pics_favorited,
    class_name: 'Pic',
    through: :fav_pics

end

class FavPic < ActiveRecord::Base
  belongs_to :user
  belongs_to :pic
end

class Pic < ActiveRecord::Base
  has_many :fav_pics
  has_many :fav_users,
    class_name: 'User',
    through: :fav_pics
end

and here's my template:

<% if current_user %>
  <%= form_tag(root_path, :method => "get") do %>
    <p>
      <%= text_field_tag :username, params[:username] %>
      <%= submit_tag "Search", :name => nil %>
    </p>
  <% end %>

  <ul>
    <% @mentions.each do |mention| %>
      <li>
        <%= mention.text %>
        <div class="row">
        <% mention.media.each do |media| %>

          <div class="col-xs-3">
            <%=image_tag(media.media_url, class:"img-responsive")%>
            <a href="#" class="fav-img"><i class="fa fa-star fa-2x"></i></a>
          </div>

        <% end %>
        </div>
      </li>
    <% end %>
  </ul>
<% else %>
  <p>
    Sign in to be able to use the app.
  </p>
<% end %>

current_user is a user signed in through Twitter and @mentions is a list of tweets that has the username inputed in the form mentioned. media.media_url is a picture url that is associated with that tweet.

I am trying to get that link (or whatever way it's done in Rails) to add that media URL into the DB so I can list all the images at a separate URL.


Querying a Postgres array of integers in Rails


my model has a pg array which I use to store integers

Querying using the methods I found from other questions yields errors or gives empty results

MyModel.where("? = ANY (myarray)", 42)

gives

PG::UndefinedFunction: ERROR:  operator does not exist: integer = text

and

 MyModel.where("myarray @> '{?}'", 42)

gives an empty results, yet I do have a model with 42 as one of the ints in the array

#<MyModel:0x007f9a77dd5608> {
                :id => 170,
      :myarray => [
    [0] 42,
    [1] 43,
    [2] 58,
    [3] 61,
    [4] 63
  ]

Is there a special way to query integers(or floats) within a postgres array in Rails?

the migration

class AddMyarrayToMyModel < ActiveRecord::Migration
  def change
    add_column :my_models, :myarray, :integer, array: true, default: []
    add_index  :my_models, :myarray, using: 'gin'
  end
end

and schema

t.integer  "myarray",                 default: [],              array: true


ActiveRecord complex calculation - how to solve it the rails way?


Currently I'm trying to figure out how to do a calculation the proper and best way using Rails 4.1.

(Simplified example)

Movement (ActiveRecord Model)

id: integer
paid_at: datetime
value: decimal
debit_account_id: references
credit_account_id: references
category_id: references
...

The Goal

I want a four column list as result, having:

  1. The paid_at date (grouped by)
  2. The sum of all values for the paid_at date, IF condition ONE is true
  3. The sum of all values for the paid_at date, IF condition TWO is true
  4. The difference of both values (Column 2 minus Column 3)

Conditions may be different, an easy case would be:

  • Condition 1: debit_account_id IN (3, 4)
  • Condition 2: credit_account_id IN (3, 4)
  • Just another one: Any field of a joined account must have a field match a value
  • ...

Example result

 date       | earnings | spendings |  total |
 -----------+----------+-----------+--------+
 2015-01-01 |   120.00 |     50.00 |  70.00 |
 2015-01-05 |     0.00 |     10.00 | -10.00 |
 2015-01-06 |   100.00 |      0.00 | 100.00 |
 ...

One possible (ugly) SQL way

SELECT
  DATE(`paid_at`) AS `date`,
  SUM(IF(credit_account_id IN(:credit_accounts), value, 0)) AS `earnings`,
  SUM(IF(debit_account_id IN(:debit_accounts), value, 0)) AS `spendings`,
  SUM(IF(credit_account_id IN(:credit_accounts), value, 0)) - SUM(IF(debit_account_id IN(:debit_accounts), value, 0)) AS `total`
FROM 
  movements
WHERE
  credit_account_id IN (:credit_accounts)
OR
  debit_account_id IN (:debit_accounts)
GROUP BY `date`
ORDER BY `date`;

The question

How can I get the expected result in a better way? And how to do it using Rails?

~~ Thank you in advance for any help! :D ~~


How to deauthorize/disconnect Stripe Connect accounts in Rails


I was looking for quite a long time for a good example on how to de-authorize / disconnect a Stripe Connect account in my Rails app. Perhaps for those that are well versed in making external POST requests, this is trivial, but I'm new and this seemed so hard for someone new to manually crafting POST requests. :)

I'm using the omniauth-stripe-connect gem, which is excellent for connecting an account with Stripe connect. It doesn't appear to have built-in functionality for disconnecting accounts.

Stripe's own documentation says to simply do a POST to their deauthorize URL. But their example is a cURL command, which you can't use natively in Rails. Or rather, it's not advised.

curl http://ift.tt/1b1lNAy \
   -u {YOUR_SECRET_KEY}: \
   -d client_id=ca_5ry8QONyVRqZAJcezVxwUWlGcJAR7cW1 \
   -d stripe_user_id=acct_llriadrqho6HXC

What's the best way to perform that POST in Rails?


RoR on Heroku - Emails not getting confirmed after clicking confirm link


Okay, so I created an app with registration system. I successfully deployed the app on Heroku. I can register a user and the confirm links go to their inbox. But when they click the link, it shows "Something went wrong..." on heroku.

the confirm link is like this: http://ift.tt/1bEOsN5

Would really appreciate if someone would give a reply!

My users controller:

def create


 @user = User.create(user_params)

  if @user.save
    UserMailer.registration_confirmation(@user).deliver
    flash[:success] = "Please confirm email"
    redirect_to root_url
  else
    flash[:error] = "Something went wrong..."
    render 'new'
  end
end

def confirm_email
user = User.find_by_confirm_token(params[:id])
if user
  user.email_activate
  flash[:success] = "Welcome to the Sample App! Your email has been confirmed.
  Please sign in to continue."
  redirect_to signin_url
else
  flash[:error] = "Sorry. User does not exist"
  redirect_to root_url
end

private

def user_params
  params.require(:user).permit(:name, :username, :email, :password, :password_confirmation, :avatar_url)
end

end

My users.rb

require 'digest/md5'

class User < ActiveRecord::Base

before_create :confirmation_token

before_validation :prep_email

    def create_avatar_url
        self.avatar_url = "http://ift.tt/RKx790"
    end

has_secure_password

validates :name, presence: true
validates :username, uniqueness: true, presence: true
validates :email, uniqueness: true, presence: true, format: { with: /\A[\w.+-]+@([\w]+.)+\w+\z/ }

def email_activate
    self.email_confirmed = true
    self.confirm_token = nil
    save!(:validate => false)
end

private

def prep_email
    self.email = self.email.strip.downcase if self.email
end

def confirmation_token
  if self.confirm_token.blank?
      self.confirm_token = SecureRandom.urlsafe_base64.to_s
  end
end

The sessions controller:

    def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
  if user.email_confirmed
    session[:user_id] = user.id
    redirect_to root_url, notice: "Logged in!"
else
    flash.now[:error] = 'Please activate your account by following the 
    instructions in the account confirmation email you received to proceed'
end


else
    flash.now[:error] = "Invalid user/pass"
  end
  end

  def destroy
    session.delete(:user_id)
    redirect_to root_url, notice: "Logged out."
  end

The app/mailers/user_mailer.rb

class UserMailer < ActionMailer::Base

default :from => "no-reply@domain.com"

def registration_confirmation(user)
    @user = user
    mail(:to => "#{user.name} <#{user.email}>", :subject => "Registration Confirmation")
end

end

Also added this to my routes file

     resources :users do
    member do
      get :confirm_email
    end

 end

Also added a text.erb file in my app/views/user_mailer/registration_confirmation.text.erb

Hi <%= @user.name %>,

Thanks for registering! To confirm your registration click the URL below.

<%= confirm_email_user_url(@user.confirm_token) %>

SMTP settings in developments.rb

      # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.default_url_options = {:host => "localhost:3000"}
  config.action_mailer.delivery_method = :smtp 
  config.action_mailer.smtp_settings = { 
    address: 'smtp.gmail.com', 
    port: 587, 
    domain: 'gmail.com', 
    user_name: 'mygmail@gmail.com', 
    password: 'mypassword', 
    authentication: 'plain', 
    enable_starttls_auto: true
   }

I tried to tail my heroku logs (heroku logs --tail) and I was monitoring the logs as I was registering. It gave me a 500 status error on my logs.

2015-04-25T08:06:21.545018+00:00 heroku[web.1]: State changed from starting to up

2015-04-25T08:06:22.709790+00:00 heroku[router]: at=info method=GET path="/" host=keplarblog4.heroku
app.com request_id=d1497cc9-02f1-4b55-8f72-a2efd95faf7a fwd="117.102.24.185" dyno=web.1 connect=0ms
service=267ms status=200 bytes=2847

2015-04-25T08:06:23.174505+00:00 heroku[router]: at=info method=GET path="/less.js" host=keplarblog4
.herokuapp.com request_id=1d6643da-a068-48e0-bc7f-1fc9c18af1af fwd="117.102.24.185" dyno=web.1 conne
ct=0ms service=6ms status=304 bytes=133

2015-04-25T08:06:23.172282+00:00 heroku[router]: at=info method=GET path="/gfx/logo.png" host=keplar
blog4.herokuapp.com request_id=abd50fb2-6861-47bb-b884-6c367d35d857 fwd="117.102.24.185" dyno=web.1
connect=0ms service=8ms status=304 bytes=133

2015-04-25T08:06:23.629123+00:00 heroku[router]: at=info method=GET path="/gfx/logo-nettuts.png" hos
t=keplarblog4.herokuapp.com request_id=77932ef2-842e-453d-b12b-fc634394ff91 fwd="117.102.24.185" dyn
o=web.1 connect=0ms service=4ms status=304 bytes=133

2015-04-25T08:06:23.701511+00:00 heroku[router]: at=info method=GET path="/style.less" host=keplarbl
og4.herokuapp.com request_id=d28896bf-abef-4d8c-bb79-a6a3788435aa fwd="117.102.24.185" dyno=web.1 co
nnect=1ms service=3ms status=304 bytes=133

2015-04-25T08:06:23.627140+00:00 heroku[router]: at=info method=GET path="/gfx/frog.jpg" host=keplar
blog4.herokuapp.com request_id=6a33e5cd-c014-4e92-a60e-2d5ebeb1b866 fwd="117.102.24.185" dyno=web.1
connect=0ms service=7ms status=304 bytes=133

2015-04-25T08:06:24.014723+00:00 heroku[router]: at=info method=GET path="/gfx/bg-header.png" host=k
eplarblog4.herokuapp.com request_id=9ab6b848-e862-4632-820d-fb9e900f6b61 fwd="117.102.24.185" dyno=w
eb.1 connect=0ms service=7ms status=304 bytes=133

2015-04-25T08:06:24.027774+00:00 heroku[router]: at=info method=GET path="/gfx/bg-footer.png" host=k
eplarblog4.herokuapp.com request_id=2fcb8907-9790-4c7c-84e9-e7f00f461110 fwd="117.102.24.185" dyno=w
eb.1 connect=1ms service=3ms status=304 bytes=133

2015-04-25T08:06:24.007494+00:00 heroku[router]: at=info method=GET path="/gfx/bg.png" host=keplarbl
og4.herokuapp.com request_id=5b210759-353a-41a1-b66a-47a4f4da16d8 fwd="117.102.24.185" dyno=web.1 co
nnect=1ms service=7ms status=304 bytes=133

2015-04-25T08:06:24.353070+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=keplarb
log4.herokuapp.com request_id=8fc598ef-7e97-4873-94f1-09505a49088b fwd="117.102.24.185" dyno=web.1 c
onnect=0ms service=5ms status=304 bytes=133

2015-04-25T08:07:33.733667+00:00 heroku[router]: at=info method=POST path="/users" host=keplarblog4.
herokuapp.com request_id=d9d4685f-9aab-404a-874d-ebcd3f543573 fwd="117.102.24.185" dyno=web.1 connec
t=0ms service=3262ms status=302 bytes=1033

2015-04-25T08:07:34.035847+00:00 heroku[router]: at=info method=GET path="/" host=keplarblog4.heroku
app.com request_id=d090ea4d-20e4-4ca4-a668-ecb0831e2962 fwd="117.102.24.185" dyno=web.1 connect=0ms
service=18ms status=200 bytes=3049

2015-04-25T08:08:10.065104+00:00 heroku[router]: at=info method=GET path="/users/5gOyuWA3-rqDG8WhZMJ
YjQ/confirm_email" host=keplarblog4.herokuapp.com request_id=ee307920-1157-4037-8d89-7d6b652965be fw
d="117.102.24.185" dyno=web.1 connect=0ms service=27ms status=500 bytes=1754

Thanks in advance!


Rails-settings-cached reverts to default


My app is now going to production and rails-cached-settings after some time expires some configurations I've made. Can anyone help?


Rails render partial as widget over ajax using jsonp


I've looked at quite a few other answers on here, but I'm still struggling a bit to figure out how to set up my Rails widget.

I have this code in my widget controller:

  def widget
    status = Company.friendly.find(params[:id]).widget.active
    body = to_json_value(render_to_string('companies/_widget', locals: { profile: self.profile }))

    render json: { status: status, html: body }
  end

  private

  def to_json_value(str)
    str.gsub!("\"", "\\\"")
    str.gsub!(/\n+/, " ")
    str
  end

The self.profile method just sets up a list of variables that get passed to the partial.

What I want to do is give a user a Javascript script tag that they can embed on their (external) website. When a user hits that page, the script will make an AJAX call to the widget controller and if the widget is turned on, it will receive a string of html to be rendered on the page.

So far I've got the widget controller to return a json object with the status and the html string. What I'm wondering is, how do I set up the js file that the user embeds on their page (ideally without relying on jQuery)?

I should note that the widget will show different information depending on what company (Rails model) it belongs to. I was thinking that this might just be pulled in from params like so:

<script src="http://ift.tt/1GuShkN" type="text/javascript"></script>

I'm also not sure where this widget.js.erb script should live in my rails app. Here is what I have so far for my widget.js.erb:

$.ajax({
 type: 'GET',
 url: 'http://ift.tt/1IWFXr0 params[:company] %>/widget',
 data: {
  html: data[key]['html']
 },
dataType: 'json',
  success: function(data) {
    $('#company-widget').html(data.html);
 }
});


How to validate the number of children records?


I have Rails 4 app with two models.

class User 
  has_many :bids
end

class Bid
  belongs_to :user
end 

A User can only create one bid per week, so I added the following to the Bid table

add_column :bids, :expiry, :datetime, default: DateTime.current.end_of_week

and the following scopes to the Bid model

scope :default, -> { order('bids.created_at DESC') }
scope :active, -> { default.where('expiry > ?', Date.today ) }

I can now prevent a User creating multiple Bids at the controller level like so:

class BidsController
  def new
    if current_user.bids.active.any?
      flash[:notice] = "You already have an active Bid. You can edit it here."
      redirect_to edit_bid_path(current_user.bids.active.last)
    else
      @bid = Bid.new
      respond_with(@bid)
    end
  end
end

But what is the best approach for validating this at the model level?

I've been trying to set up a custom validation, but am struggling to see the best way to set this up so that the current_user is available to the method. Also, am I adding errors to the correct object?

class Bid
  validate :validates_number_of_active_bids
  def validates_number_of_active_bids
    if Bid.active.where(user_id: current_user).any?
      errors.add(:bid, "too much") 
    end
  end 
end


Rails button_to with image and actions


I want to show button with image. I have this code

<%= image_submit_tag "down.png", controller: "posts", action: "votedown", post_id: post.id, topic_id: post.topic_id, class: "xta" %>

Its visible properly but not calling action "votedown"

In my routes I have

post '/votedown', to: 'posts#votedown


How can I update particular fields of model with validation in Ruby on Rails?


There is an AcviteRecord Model named User like this:

class User < ActiveRecord::Base
  validates :name, :presence => true
  validates :email, :presence => true, :uniqueness => true

  validates :plain_password, :presence => true, :confirmation => true
  validates :plain_password_confirmation, :presence => true
  #...other codes
end

It requires that the update of name and email and the update of password are separated.

When only update name and password, using update or update_attributes will cause password validation which is not needed. But using update_attribute will save name and email without validation.

Are there any ways to update particular fields of model with validation without causing the other fields' validation?


Keyword Auto Translator Gem?


I'm a Ruby and Rails newbie and I've been tasked with designing a simple messenger application that takes incoming messages, parses the message for keywords, and translates the messages based on the internal structure to the recipient . I've found resources like Twillo ( This is exactly what I'm looking for http://ift.tt/1xmvv5n) but was wondering if there was a gem or other suggestions you could make that would help me make this small dream a reality. Thanks a bunch!


Turbolinks 3 and render a partial


I'm excited about turbolinks3(it allows you to render only a partial and not reload all the body) You can read more about it from here: http://ift.tt/1HDKIqP It's amazing but I've a problem: In browsers that doesn't support pushState(example ie8/9), I don't know how manage the behavior. It give me this error on IE8:

Could not set the innerHTML property. Invalid target element for this operation.

My Controller code is:

  def create
    @post = Post.find(params[:post_id])

    if @post.comments.create(comment_params)
      render '_comment', change: [:comments, :super_test], layout: false, :locals => { comment: @post.comments.last }
    else
      render json:'error'
    end
  end

A 'solution' could be that I do:

redirect_to @post, change: [:comments, :super_test]

But then the problem is that it reply with a lot of data that I don't need!(and the response time is bigger) So I reallt want find another solution.

How I can resolve this problem ? I've thought about 2 solution: 1) Use history.js / modernizr for polyfill the pushState on old browsers

  • But I've tried but I always get the same error(like if I don't have modernizr)

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0) Timestamp: Sat, 25 Apr 2015 17:28:52 UTC

    Message: Could not set the innerHTML property. Invalid target element for this operation. Line: 26 Char: 30464 Code: 0 URI: http://ift.tt/1Dn902f

2) Find a way for check if the request is done by turbolinks/pjax or not...and use conditional render or redirect_to

  • But I've not idea on how I can do it, because turbolinks doesn't send a specific header like does jquery-pjax

Any suggestions ? I really appreciate it!

PS: Please don't suggest me backbone/angular/ember/react, I already know them(backbone), but I want try turbolinks.


Joining multiple relationships from separate tables into one association


I have several models that are relevant to this question..

  • UserGroupPermission
  • UserGroup
  • User
  • UserPermission
  • Permission

Essentially, A User can be assigned a permission through either their UserGroup or directly. UserGroups are tied to specific permissions via the UserGroupPermission model. Users are tied to specific permissions via the UserPermission model.

The end result is to be able to call User.permissions and return every permission assigned to that user either directly or through a UserGroup.

Here is my current model

class User < ActiveRecord::Base
    belongs_to :user_group

    #Permissions
    has_many :user_permissions
    has_many :user_group_permissions, :through => :user_group
    has_many :permissions, :through => :user_group_permissions #and :user_permissions
end

I've search high and low for a solution to this, but can't seem to find my exact case. Thanks in advance!

Edit: I've been told that is unclear what I'm asking. Hopefully this will help: Basically the User has_many :permissions, :through => :user_group_permissions and :user_permissions, but you can't use an and to join the results together. I'm trying to retrieve and combine the results of both of those relations into one.


How to fix this error "undefined method `encoding' for nil:NilClassa " and get canceling subscription plan worked?


This is my first time working with Stripe and Rails and now I am trying to allow premium users to cancel their subscriptions.

I can upgrade a user from standard level to premium level with my code, but I am having issues when I attempt to downgrade a premium user to the standard level.

I have followed Stripe Ruby API References of "Cancel a subscription": http://ift.tt/1brVgNv, but I got this error when I clicked the "cancel subscription" button:

NoMethodError - undefined method encoding' for nil:NilClass: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/cgi/util.rb:7:inescape' stripe (1.21.0) lib/stripe/list_object.rb:19:in retrieve' app/controllers/subscriptions_controller.rb:55:indowngrade'

My rails version is 4.2.1.

My code:

class SubscriptionsController < ApplicationController

def create
    subscription = Subscription.new
      stripe_sub = nil
    if current_user.stripe_customer_id.blank?
      # Creates a Stripe Customer object, for associating with the charge
      customer = Stripe::Customer.create(
        email: current_user.email,
        card: params[:stripeToken],
        plan: 'premium_plan'
        )
      current_user.stripe_customer_id = customer.id
      current_user.save!
      stripe_sub = customer.subscriptions.first
    else
      customer = Stripe::Customer.retrieve(current_user.stripe_customer_id)
      stripe_sub = customer.subscriptions.create(
        plan: 'premium_plan'
        )
    end

    current_user.subid = stripe_sub.id

    current_user.subscription.save!

    update_user_to_premium
    flash[:success] = "Thank you for your subscription!"

    redirect_to root_path 

    # Handle exceptions
    rescue Stripe::CardError => e
     flash[:error] = e.message
     redirect_to new_subscriptions_path
  end


  def downgrade

    customer = Stripe::Customer.retrieve(current_user.stripe_customer_id)
    customer.subscriptions.retrieve(current_user.subid).delete

    downgrade_user_to_standard
    flash[:success] = "Sorry to see you go."
    redirect_to user_path(current_user)

  end
end

ApplitionController:

class ApplicationController < ActionController::Base
def update_user_to_premium
    current_user.update_attributes(role: "premium")
   end

   def downgrade_user_to_standard
    current_user.update_attributes(role: "standard")
   end
end

config/initializers/stripe.rb:

Rails.configuration.stripe = {
   publishable_key: ENV['STRIPE_PUBLISHABLE_KEY'],
   secret_key: ENV['STRIPE_SECRET_KEY']
 }

 # Set our app-stored secret key with Stripe
 Stripe.api_key = Rails.configuration.stripe[:secret_key]

Any help will be appreciated!

Update: Thanks for help from stacksonstacks, all I need is asserting 'subscription.user = current_user' under 'current_user.subid = stripe_sub.id', and then call subscription id with "subscription = current_user.subscription" in downgrade method. Now subscription cancelling works!


ActionController::ParameterMissing at /accounts/deposit tieing params to deposit form


I have been working on this rails 4 project since yesterday at 3pm and i have not slept. i am all out of ideas as to why this is bombing out. the error message i get is : ActionController::ParameterMissing at /accounts/deposit param is missing or the value is empty: affiliates_account

my accounts_controller looks like this:

class AccountsController < ApplicationController
#before_action :set_account, only: [:show, :edit, :deposit, :credit,     
:update, :destroy]
before_filter :set_account, only: [:show, :edit, :credit, :update, :destroy]
before_filter :authenticate_user!

respond_to :html

def index
 # @accounts = Account.all
 #@accounts = Account.where(id:current_user.id)
 if current_user.admin?
  @accounts = Account.all
  else
   @accounts = Account.where(email:current_user.email)
  end
  respond_with(@accounts)
  end

  def show
  if current_user.admin?
    @accounts = Account.all
   else
   @accounts = Account.where(email:current_user.email)
  end
  respond_with(@account)
  end

  def new
     @account = Account.new
     respond_with(@account)
  end

  def edit
    @accounts = Account.all
  end

  def create
    #  @account = Account.new(account_params)
    #@account.save
    # respond_with(@account)
  end

  def update
    @account.update(account_params)
    respond_with(@account)
  end

  def destroy
     @account.destroy
     respond_with(@account)
  end

  def withdrawl
    @account = Account.new(account_params)
    @account.email = current_user.email
    @account.user_id = current_user.id
  end

  def deposit
    @account = Account.new(account_params)
    @account.email = current_user.email
    @account.user_id = current_user.id
    respond_to do |format|
    @account.save
   end
     redirect_to :root
   end 


     private
     def set_account
        #@accounts = Account.where(id:current_user.id)
        @account = Account.find(params[:id])
     end

     def account_params
       # params[:account]
       params.require(:account).permit(:created_at, :email, :credit, :debit,
       :acctbal, :depotype)
     end
     end

and my Model for accounts.rb

 class Account < ActiveRecord::Base
 belongs_to :user
 validates :depotype, presence: true
 DEPOSIT_TYPES = [ "Check", "Credit card", "Purchase order" ]
 validates :depotype, inclusion: DEPOSIT_TYPES

 def final_acct_bal 
   accounts.to_a.sum {|account| account.final_acct_price}
   end
 end

and i created a new deposit.html.erb because the new.html.erb kept giving me a weird error and someone mention that the create method is tied to that and that i should create a seperate form page. so i did and now im having a tough time linking my deposit action method to that page so that my "add funds" button on my index.html.erb will go to it. and perform the requested actions accordingly.

<h1>Editing account</h1>

<%= render 'form' %>

<%= link_to 'Show', @account %> |
<%= link_to 'Back', accounts_path %>

my index.html.erb with that link_to button

<div class="container">
<h1>Listing Accounts Inquiries</h1>

<h2>Your Account information</h2>
  <table border="3">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Date</th>
                <th>Credit</th>
                <th>Debit</th>
                <th>Account Balance</th>
            </tr>
    </thead>
        <tbody>      
             <% @accounts.each do |account| %>   
                <tr>
                    <td><%= account.created_at %></td>
                    <td><b><font color="green"><%=
                         number_to_currency(account.credit)%></b></td>      
                    <td><b><font color="red"><%= 
                         number_to_currency(account.debit)%></font></b></td>    
                    <td><b><%= number_to_currency(account.acctbal)%></b>
               </td>        
                </tr>
                 <% end %>
            <tbody>     
        </table>
    </table>

    <%= link_to "Add Funds", deposit_accounts_path, method: :post, :class =>
       "btn btn-primary btn-sm" %>

    <table>
    <thead>
  <tr>
  <th colspan="3"></th>
  </tr>
  </thead>
     <% if can? :manage, Users%>
     <tbody>
       <% @accounts.each do |account| %>
      <tr>
    <td><%= link_to 'Show', account %></td>
    <td><%= link_to 'Edit', edit_account_path(account) %></td>
    <td><%= link_to 'Destroy', account, method: :delete, data: { confirm:
         'Are you sure?' } %></td>
       </tr>
    <% end %>
  </tbody>
  </table>

  <br>

   </div>
  <% end %>

i think this part of the params is hosing it up, params.require(:account) but i dont know what to do to change this so that it works and nothing else breaks


Querying any member of a Postgres array type in Rails 4


Everywhere I looked there were 2 examples

either

Book.where("'history' = ANY (subjects)")

to query a book with a specific subject in the subject array

or

 Book.where("subjects @> ?", '{'history', 'drama'}')

to query books that the subjects array has both history and drama

How do I query for books that has either history or drama or both?


Thin dependency workaround for mailcatcher gem


In order to test emails in my rails app, I tried adding the mailcatcher gem. When I first ran mailcatcher, I got an error with eventmachine that effectively broke the mailcatcher server. I realized this was due to the version of mailcatcher being used, but after I tried to update to a newer version, I am having dependency issues. I got the following error when I ran bundle:

Bundler could not find compatible versions for gem "thin":
  In Gemfile:
    mailcatcher (>= 0.6.1) ruby depends on
      thin (~> 1.5.0) ruby

    thin (1.6.3)

Is there any possible workaround, or other suggestions? I don't want to lock thin at 1.5.0. Older versions of mailcatcher are broken, and the updated versions aren't playing nicely with thin. I may just find another gem to test emails...


workers vs jobs using Sidekiq, Redis, Whenever and ActiveJob Rails 4.2


I am a little confused as to where "jobs" and "workers" fall in the workflow of background processing. I'm trying to write my first rake tasks that send periodic emails and almost all tutorials are pre-rails 4.2, and so they suggest I create a Sidekiq worker, etc....though now, that Active Job is rolled into Rails 4.2...I think I can just create a Job...am I correct? I am using Redis, Sidekiq, Rails 4.2 and PG. I am using the Whenever gem for scheduling

Here is what I am doing to create these recurring emails:

send_test_job.rb

class SendTestJob < ActiveJob::Base
  queue_as :default

rescue_from(StandardError) do |exception|
    notify_failed_job_to_manager(exception)
  end
 # perform(users, project_archives, rakelogs, projects, user_archives)
    def perform
        @users = User.all
        @subject ="Test Email"
        if   @users.present? 
            AdminNotifierMailer.hourly_roundup(@users, @projects, @subject).deliver_later
        else
        end
    end

 private

  def notify_failed_job_to_manager(exception)
    AdminNotifierMailer.job_failed(User.find(?), exception).deliver_later
  end

end

scheduler.rake

namespace :admin do

    desc "sends a test email"
    task :send_test => :environment do
        puts "sending Test Job"
        SendTestJob.perform_later 
        puts "done"
    end

end

config/schedule.rb (for whenever gem)

every 1.minutes do
  rake "admin:send_test", :output => {:error => 'error.log', :standard => 'cron.log'}
end

sidekiq.yml (the code hinting color on this is screwy...so this may be an issue)

---
:concurrency: 25
:pidfile: ./tmp/pids/sidekiq.pid
:logfile: ./log/sidekiq.log
:queues:
  - default
  - [high_priority, 2]

As you can see I have no workers...but that's because I can't really figure out where to put one or if I need one.


How can I find gem to track spammers ?


I am implementing website on ruby on rails and i need a gem to help me to track spammers on the website or can i use ahoy gem to help me ? p.s the website for selling products .


Rails + Angular ngmap assets:precompile fails ExecJS::ProgramError: Unexpected token: operator (<)


I have a problem with using angularjs-google-maps in production enviorment. In development everything is ok, but I can't compile assets on production server.

I noticed that there are a lot of unnecessary files included with ngmap gem.

RAILS_ENV=production rake --trace assets:precompile

** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
** Execute assets:precompile
I, [2015-04-25T17:57:56.079875 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/app-94252b272926e36fbae605d3d25133aa.js
I, [2015-04-25T17:58:28.502049 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/application-8fbf87fa5189cd52f0ea4f4a696ea739.js
I, [2015-04-25T17:58:28.897157 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/login_ctrl-d03e64c2c537a8fedd74d00cd8f4f6ff.js
I, [2015-04-25T17:58:28.905913 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/loginmodalinstance-8eb12faf836219219357c3abf2fed41f.js
I, [2015-04-25T17:58:28.913854 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/mainpage_ctrl-8c49ca945cddea3c869c6851bfb4d399.js
I, [2015-04-25T17:58:28.921329 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/navbar_ctrl-ef36cc74dbba667d5f39d2c3e6d8e146.js
I, [2015-04-25T17:58:28.931117 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/ranikng_ctrl-1a527c570e1209a2e99dc304701b4946.js
I, [2015-04-25T17:58:28.939972 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/controllers/trips_ctrl-f979593576fb3c3cebaaa8e6a844730d.js
I, [2015-04-25T17:58:28.946519 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/routes-528f733517a0a0490706a08c0344e9db.js
I, [2015-04-25T17:58:28.957540 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/services/trip-5f57c1cefa483c3a5e0caf44d59caf9a.js
I, [2015-04-25T17:58:28.963135 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/users-18594645a42e53a5242d1f464935c3d7.js
I, [2015-04-25T17:58:46.408155 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/application-3d2a2d36862b13dabb63aa1e16b2cb78.css
I, [2015-04-25T17:58:46.420625 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/modules/_headers-545910712798558def0961f9e9ee23c1.css
I, [2015-04-25T17:58:46.429595 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/modules/_ranking-6458bb36166ae950b1cfc2401b4fdb7f.css
I, [2015-04-25T17:58:46.493008 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/mystyle-70cce5ae11a71b412e69180a968d333d.css
I, [2015-04-25T17:58:46.497582 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/trips-86520fe950e8f54c4a42705ca501dccd.css
I, [2015-04-25T17:58:46.501622 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/users-86520fe950e8f54c4a42705ca501dccd.css
I, [2015-04-25T17:58:46.509965 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/utilities/_general-c557520ddf99f29f0865b15ec8f9e106.css
I, [2015-04-25T17:58:54.369379 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/welcome_page-934dc0e3ac9c29ad97d1cc13478e3ccd.css
I, [2015-04-25T17:58:54.386571 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/welcome_page/_form-b3be3aadee985aa02c0d3b25e39510d1.css
I, [2015-04-25T17:58:54.405405 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/welcome_page/_layout-9bf9b8f6208102ce8ae98c15753f8953.css
I, [2015-04-25T17:58:54.414697 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ranking/index-f5717a5fb7e467d61618d90a75b893c6.js
I, [2015-04-25T17:58:54.421676 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/trips/index-23bb50797f5dbc636498a4e582aabb3d.js
I, [2015-04-25T17:58:54.502179 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/trips/mytrips-e143061c1600e83852903ca9a10a5b39.js
I, [2015-04-25T17:58:54.910150 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap-62f3230933e8e7b06478ba1aa35cdd87.js
I, [2015-04-25T17:58:55.405234 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap/ng-map.debug-2cd1a77a370dde9a38d8143f253d0f7a.js
I, [2015-04-25T17:58:55.782427 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap/ng-map-62f3230933e8e7b06478ba1aa35cdd87.js
I, [2015-04-25T17:58:55.916746 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap/config/jsdoc/template/static/styles/jsdoc-default-587683882678b05f6fa1959d2ba36ead.css
I, [2015-04-25T17:58:55.970232 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap/config/jsdoc/template/static/styles/prettify-jsdoc-bab63eaf363431eea30f9696ec25899c.css
I, [2015-04-25T17:58:56.095053 #16681]  INFO -- : Writing /home/mikes/rails/EcoDriver/public/assets/ngmap/config/jsdoc/template/static/styles/prettify-tomorrow-20b352776b83ef223a0569a4a579c162.css
rake aborted!
ExecJS::ProgramError: Unexpected token: operator (<) (line: 1, col: 0, pos: 0)

Error
    at new JS_Parse_Error (<eval>:2359:10623)
    at js_error (<eval>:2359:10842)
    at croak (<eval>:2359:19086)
    at token_error (<eval>:2359:19223)
    at unexpected (<eval>:2359:19311)
    at expr_atom (<eval>:2359:27526)
    at maybe_unary (<eval>:2359:30019)
    at expr_ops (<eval>:2359:30777)
    at maybe_conditional (<eval>:2359:30869)
    at maybe_assign (<eval>:2359:31312)
  (in /var/lib/gems/1.9.1/gems/rails-assets-ngmap-1.7.7/app/assets/templates/ngmap/testapp/aerial-rotate.html)new JS_Parse_Error ((execjs):2359:10623)
js_error ((execjs):2359:10842)
croak ((execjs):2359:19086)
token_error ((execjs):2359:19223)
unexpected ((execjs):2359:19311)
expr_atom ((execjs):2359:27526)
maybe_unary ((execjs):2359:30019)
expr_ops ((execjs):2359:30777)
maybe_conditional ((execjs):2359:30869)
maybe_assign ((execjs):2359:31312)
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:47:in `rescue in block in call'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:44:in `block in call'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:75:in `block in lock'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:73:in `call'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:73:in `Locker'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:73:in `lock'
/var/lib/gems/1.9.1/gems/execjs-2.4.0/lib/execjs/ruby_racer_runtime.rb:43:in `call'
/var/lib/gems/1.9.1/gems/uglifier-2.7.1/lib/uglifier.rb:212:in `run_uglifyjs'
/var/lib/gems/1.9.1/gems/uglifier-2.7.1/lib/uglifier.rb:179:in `compile'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/compressing.rb:63:in `block (2 levels) in js_compressor='
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/processor.rb:29:in `call'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/processor.rb:29:in `evaluate'
/var/lib/gems/1.9.1/gems/tilt-1.4.1/lib/tilt/template.rb:103:in `render'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/context.rb:197:in `block in evaluate'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/context.rb:194:in `each'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/context.rb:194:in `evaluate'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/bundled_asset.rb:25:in `initialize'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/base.rb:377:in `new'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/base.rb:377:in `build_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/index.rb:94:in `block in build_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/caching.rb:58:in `cache_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/index.rb:93:in `build_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/base.rb:287:in `find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/index.rb:61:in `find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:211:in `block in find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:257:in `benchmark'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:210:in `find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:119:in `block in compile'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:118:in `each'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/sprockets/manifest.rb:118:in `compile'
/var/lib/gems/1.9.1/gems/sprockets-rails-2.2.4/lib/sprockets/rails/task.rb:70:in `block (3 levels) in define'
/var/lib/gems/1.9.1/gems/sprockets-2.12.3/lib/rake/sprocketstask.rb:146:in `with_logger'
/var/lib/gems/1.9.1/gems/sprockets-rails-2.2.4/lib/sprockets/rails/task.rb:69:in `block (2 levels) in define'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:240:in `call'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:240:in `block in execute'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:235:in `each'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:235:in `execute'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:179:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:172:in `invoke_with_call_chain'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/task.rb:165:in `invoke'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:150:in `invoke_task'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:106:in `each'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:106:in `block in top_level'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:115:in `run_with_threads'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:100:in `top_level'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:78:in `block in run'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:176:in `standard_exception_handling'
/var/lib/gems/1.9.1/gems/rake-10.4.2/lib/rake/application.rb:75:in `run'
/var/lib/gems/1.9.1/gems/rake-10.4.2/bin/rake:33:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<main>'
Tasks: TOP => assets:precompile


Rails is there a way to collect all routes


I am using this as an example: http://ift.tt/1mgtD7V

The route file looks like:

Rails.application.routes.draw do
  root 'static_pages#home'

  resources :users do
    member do
      get :following, :followers
    end
  end
  resources :sessions,      only: [:new, :create, :destroy]
  resources :tweets,        only: [:index, :create, :destroy]
  resources :relationships, only: [:create, :destroy]

  get    'signup'   => 'users#new'
  get    'signin'   => 'sessions#new'
  delete 'signout'  => 'sessions#destroy'
  get    'about'    => 'static_pages#about'

  match '*path' => 'application#routing_error', via: :all
end

It appears that in some controllers there are comments mentioning which route it uses, however it's not specified in the route file. For instance:

 # GET /users
  def index
    @users = User.all
  end

  # GET /users/1
  def show
    @tweet = current_user.tweets.build if signed_in?
    @feed_items = @user.tweets.paginate(page: params[:page])
  end

(in users_controller.rb)

My question is, how does rails app know that there is an endpoint here? I would like to know whether I can actually collect all the routes in one file?


Wicked, the second can not get the correct path (show action)


So I am trying to build a wicked wizard. I have User and Boat Model. When Boat model is created, all the steps starts. The first #show action works fine for the first step. But I have a problem with the `second step.

Here is my

    #routes
     resources :users
      resources :boats, except: :destroy do
          resources :pictures
      end


  resources :boat_steps 



#boat_steps controller

class BoatStepsController < ApplicationController
    include Wicked::Wizard


    before_action :logged_in_user
    steps :model, :pricing, :description, :picture

    def show
        @boat = current_user.boats.last
        render_wizard
    end

    def update
        @boat = current_user.boats.last
        @boat.update_attributes(params[:boat])
        render_wizard @boat
    end


end

#model.html.erb
<% provide(:title, "List Boat") %>
<h1>List your Boat</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <p>AHoy! <%= current_user.name %>. It only takes 5 mins to fill the form!.</p>
  </br></br>

  </br>
    <%= form_for(@boat, url: wizard_path, method: put) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

      <h2>Brand & Model</h2>
      <%= f.label :brand %>
      <%= f.text_field :brand, placeholder: "Brand Name", class: 'form-control' %>

      <%= f.label :model %>
      <%= f.text_field :model,  placeholder: "Model", class: 'form-control' %>

      <%= f.label :boat_category, "Boat Category" %>

      <% if @boat.boat_type == "Power" %>
      <%= f.collection_select(:boat_category,  Power.all, :name, :name, {:prompt   => "Select a Category"}) %>
      <% else %>
      <%= f.collection_select(:boat_category,  Sail.all, :name, :name, {:prompt   => "Select a Category"}) %>
      <% end %>


      <% if @boat.boat_type == "Sail" %>
      <%= f.label :mast_material, "Mast Material" %>
      <%= f.collection_select(:mast_material,  Mast.all, :name, :name, {:prompt   => "Select a Material"}) %>
      <% end %>
      <%= f.label :hull_material, "Hull Material" %>
      <%= f.collection_select(:hull_material,  Hull.all, :name, :name, {:prompt   => "Select a Material"}) %>


      <%= f.label :boat_length, "Boat Length" %>
      <%= f.number_field :boat_length, placeholder: "Ex. 15", max: '50',  class: 'form-control' %>


      <%= f.submit "Next", class: "btn btn-primary" %>
    <% end %>


  </div>
</div>

And here is the

#pricing.html.erb
<h2>Pricing</h2>

<%= form_for (@boat, url: wizard_path) do |f| %>
      <%= f.radio_button(:captained, "Captained") %>
      <%= f.label(:captained_captained, "Captained") %>
      <%= f.radio_button(:captained, "Bareboat") %>
      <%= f.label(:captained_bareboat, "Bareboat") %>

      <%= f.label :daily_price, "Daily Price (TL)" %>
      <%= f.number_field :daily_price, placeholder: "Ex. 180.00", max: '1000.00',  class: 'form-control' %>

      <%= f.submit "Next", class: "btn btn-primary" %>
 <% end %>

Lastly,

#boats controller
 def new
    @boat = Boat.new
  end

  def create
   @boat = current_user.boats.new(boat_params) if logged_in?
    if @boat.save
      #flash[:success] = "Continue from here"
      redirect_to boat_steps_path
    else
      render 'new' 
    end
  end

  def show
    @boat = Boat.find(params[:id])

  end


  def edit
    @boat = Boat.find(params[:id])
  end


  def update
     @boat = Boat.find(params[:id])
    if @boat.update_attributes(boat_params)
      flash[:success] = "The Boat Saved"
      redirect_to root_path
    else
      render 'edit'
    end
  end

So, the first form, (model.html.erb) opens as; http://localhost:3000/boat_steps/model, when I click next, the url becomes;

http://localhost:3000/boat_steps/id=157 

It is because of the #show action (@boat = current_user.boats.last) I believe but I could not find a way to do it. If I make it @boat = current_user.boats then I receive undefined method to_key'

Here is the log when I use ; @boat = current_user.boats.last

Started PATCH "/boat_steps/model" for ::1 at 2015-04-25 19:48:39 +0300
Processing by BoatStepsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"m5MY9OjdHLLplnzHyO5VDmLwx8hboMOKrtPRGuBnTNzsTh1F+DlVWxKoDL9smYXYpE8bHln6HHEtnF3NpJl6HQ==", "boat"=>{"brand"=>"A & M Manufacturing Inc", "model"=>"LAGOON 14 SPORT/FO [14']", "boat_category"=>"", "mast_material"=>"", "hull_material"=>"", "boat_length"=>"31"}, "commit"=>"Next", "id"=>"model"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Boat Load (0.1ms)  SELECT  "boats".* FROM "boats" WHERE "boats"."user_id" = ?  ORDER BY "boats"."id" DESC LIMIT 1  [["user_id", 1]]
Completed 500 Internal Server Error in 4ms

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
  app/controllers/boat_steps_controller.rb:15:in `update

Actually, the url should become, http://localhost:3000/boat_steps/pricing

thank you


How to program routes to a model ruby on rails?


I have a website that translates DNA codons to MRNA codons. I created am immutable immutable 64 row DB model with 3 columns with sqlite, which I then preceeded to seed. Basically, what I want is the user to input a string into a text-area and break the string into 3 character string fragments "ttcttaatt..." --> (dnaCodon) [ttc][tta][att] --> that match to the database returning matched results (mrnaCodon ) [uuc] [uua] [auu]. I created a search form on one of my static pages

I am running into trouble now with my routes in the search form. I want to query the search and then return it either to the same page, or a different page- whichever method is easier and makes more sense. I initially created my DB without scaffolding because I don't want it accessible by users for alterations. I ended up creating a scaffolding folder so I dunno why it's not connecting to the database. My page refreshes but does not return the DB query

app/controllers/aa_data_bases_controller.rb

class AaDataBases < ApplicationController
  def index
     if params[:search]
    @aa_data_bases = AaDataBases.search(params[:search]).order("created_at DESC")
  else
    @aa_data_bases = AaDataBases.all.order('created_at DESC')
     end
   end
end

views/static_pages/sequence.html.erb It's in this static page that the problem route is, in form_tag("/sequence"... When I run rails server the pages loads, i can input but page refreshes and nothing happens

<% provide(:title, 'Sequence') %>
<h1>Sequence</h1>

<body>
    <div class="content-container-1" id="div3">
       <div class="container">
          <div class="row text-center">
            <h3>Add your sequence here</h3>

          </div>

           <div class="row text-center pt mb">
             <div class="col-md-6 col-md-offset-3">
                <br>

              <%= form_tag("/sequence", :method => "get", id: "search-form") do %>
              <%= text_area_tag :search, params[:search], placeholder: "Translate DNA codons...", :size =>"75x10", class: "form-control"%>
              <br>
              <%= submit_tag "Sequence Now!", class: "btn btn-large btn-primary",:name => nil  %>
               <% end %>

            </div>
        </div>
    </div>
</div>

config/routes.rb

Rails.application.routes.draw do
  root 'static_pages#home'

  match '/about', to: 'static_pages#about', via: 'get'

  match '/contact', to: 'static_pages#contact', via: 'get'

  match '/help', to: 'static_pages#help', via: 'get'

  match '/sequence', to: 'static_pages#sequence', via: 'get'

  match '/seqresults', to: 'static_pages#seqresults', via: 'get'
end

model/aa_data_bases.rb

class AaDataBases < ActiveRecord::Base
 def self.search(query)
    where("%#{query}%") 
  end
end

DB

class CreateAaDataBases < ActiveRecord::Migration
  def change
    create_table :aa_data_bases do |t|
      t.string :aaFullName
      t.string :dnaCodon
      t.string :mrnaCodon

      t.timestamps
    end
  end
end

My seeding file, there are 64 entries just like this

AaDataBases.create(aaFullName: "phenylalanine", dnaCodon:"ttt", mrnaCodon:"uuu")
AaDataBases.create(aaFullName: "phenylalanine", dnaCodon:"ttc", mrnaCodon:"uuc")
AaDataBases.create(aaFullName: "leucine", dnaCodon:"tta", mrnaCodon:"uua")
AaDataBases.create(aaFullName: "leucine", dnaCodon:"ttg", mrnaCodon:"uug")
AaDataBases.create(aaFullName: "leucine", dnaCodon:"ctt", mrnaCodon:"cuu")
AaDataBases.create(aaFullName: "leucine", dnaCodon:"ctc", mrnaCodon:"cuc")
AaDataBases.create(aaFullName: "leucine", dnaCodon:"cta", mrnaCodon:"cua")


Rails update multiple columns based on an array


I'm trying to blank out a bunch of columns in an easy-to-read formatted code. I know I could just do this:

@user = User.find(3)
@user.column1 = nil
@user.column2 = nil
@user.column3 = nil
etc...

But that doesn't seem like a very Ruby way to do things, nor is it particularly clean to read.

I'm trying to figure out why I can't just do an 'each do' array like this:

columns = [ "key", "provider", "uid", "access_code",
                "customer_id", "cc_id", "cc_brand", "cc_last4",
                "cc_expiration", "last_payment_id", "last_payment_date",
                "last_payment_amount" ]

columns.each do |record|
  @user.record = nil
end

@user.save

I receive the following error:

undefined method `record=' for #<User:0x00000003a91d18>

I know that similar questions have been asked before, but they are usually related to updated a bunch of different tables. I'm only interested in the user table.

Also, there are a lot of answers linking to http://ift.tt/1apioMa. But that's an old deprecated method that apparently bypasses callbacks. That seems rather dangerous.

Can anyone think why a simple 'each do' array won't work?


Embedding SoundCloud Widget in Ruby on Rails


I'm fairly new at integrating APIs in Ruby on Rails but I want to use Soundcloud's API to embed a player widget when provided a Soundcloud URL from a user. Right now I have the widgets embedded in my table through a test link. Each post contains string called link but I don't know how to reference it inside the controller. Or would I point to link in my view? Here's what I have so far. Any help would be appreciated.

class PostsController < ApplicationController

require 'soundcloud'

def index

    @client = Soundcloud.new(:client_id => 'xxxxx')
    @posts = Post.search(params[:search]).order(sort_column + " " + sort_direction)
    track = @client.get('/resolve', :url => post.link )
    @trackid = track.id

end


private

def set_post
    @post = Post.find(params[:id])
end

def post_params
    params.require(:post).permit(:link)
end

end

Here's the corresponding view.

<% provide(:title, 'Home') %>

<table>
  <thead>
    <tr>
      <th>Link</th>
    </tr>
  </thead>
  <tbody>
    <% @posts.each do |post| %>
      <td><div id="player"><object height="70" width="100%"><param name="movie" value="http://ift.tt/1ECyM9F @trackid %>&player_type=tiny{widgetParams}"></param>
      <param name="allowscriptaccess" value="always"></param>
      <param name="wmode" value="transparent"></param>
      <embed wmode="transparent" allowscriptaccess="always" height="18" width="100%"     src="https://player.soundcloud.com/player.swf?    url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F{trackId}&player_type=tiny{widgetParams}">    </embed></object></div></td>
    <% end %>
 </tbody>


Ruby Constantly consume external API and share output across processes


I'm writing trading bot on ruby and I need to constantly do some calculations based on Exchange's orderbook depth data across several daemons (daemons gem).

The problem is that right now I'm fetching data via Exchange's API separately in each daemon, so I ran into API calls limit (40 requests/second). That's why I'm trying to utilize ruby Drb to share orderbook data across several processes (daemons) in order to not sending unnecessary API calls.

Although I m not sure how to constantly consume API on the server side and provide the latest actual data to the client process. In the sample code below, client will get data actual at the moment when I started server

server_daemon.rb

require 'drb'    
exchange = exchange.new api_key: ENV['APIKEY'], secret_key: ENV['SECRET']
shared_orderbook = exchange.orderbook limit: 50
DRb.start_service('druby://127.0.0.1:61676', shared_orderbook)
puts 'Listening for connection… '
DRb.thread.join

client_daemon.rb

require 'drb'
DRb.start_service
puts shared_data = DRbObject.new_with_uri('druby://127.0.0.1:61676')


How top pop last element of ActiveRelation?


Say I have this query:

red_houses = user.houses.where(color: 'red')

How can I pop the last element of red_houses?

I know I can do this red_houses[1..-2], but not red_houses.pop, is there any way I am missing?

Basically I want to delete the last element and get the remaining relation without the last element on it.


Ahoy is not recording events or visits


I have installed Ahoy to give some user analytics on my rails application. I am running rails 4.1.10 and using Postgres 9.3.10

I have added the gem to my gemfile:

gem 'ahoy_matey'

And I have run :

rails generate ahoy:stores:active_record -d postgresql
rake db:migrate

As per the docs.

I also added //=require ahoy after jquery in the application.js assets file.

I was not sure if visits and events would be tracked automatically - so I went to a couple of pages and checked manually in the DB and I see no entries in the visits or ahoy_events tables. So I manually coded this into my landing page index controller action:

ahoy.track "Viewed Landing", title: "Landing page viewed"

And this line causes the following error:

NameError in LandingPageController#index
undefined local variable or method `ahoy' for #<LandingPageController:0x007fa634fee7f0>

(Listed in full here : http://ift.tt/1Fm5sTH)

Can anybody help me get ahoy logging visits and events please! Ideally I want it to track everything, automatically if there is some golden switch I need to press :)


Rails, trying to avoid duplicating code (lists of URLs)


I'm trying to simplify and DRY up my rails code so as not to duplicate lists of URLs in multiple places and have to keep them in sync. I have a controller with a method parent that has instance variables for lists of urls in different categories, i.e.

def parent
  @collection1 = [
    ["Link 1", "http://link1.com"],   
    ["Link 2,  "http://link2.com"] 
  ]
  @collection2 = [
    ["Link 3", "http://link3.com"],   
    ["Link 4,  "http://link4.com"] 
  ]
end

Then in my views I have a file parent.html.erb with code

<% @collection1.each do |link| %> 
                      <a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>
<% @collection2.each do |link| %> 
                      <a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>

But I have another view, child.html.erb that I want to just display collection 1, so

<% @collection1.each do |link| %> 
                      <a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>

But in order to do this I have to define another method in the same controller:

def child
  @collection1 = [
    ["Link 1", "http://link1.com"],   
    ["Link 2,  "http://link2.com"] 
  ]

which is the same collection as I have in the parent method. That works but then if I want to change one the links I have to change it in both places. Please advise, I am pretty new to rails but realize this can't possibly be the way you're supposed to this! Thank you.


Is it possible to perform a batch action on all of the records after filtering in activeadmin?


I need to perform a batch action on all of the records after filtering in activeadmin. I've read following question: ActiveAdmin: batch select all pages but in this case select is fairly simple. We can use just Model.all or something similar. But is it possible to select all of the records on all of the pages after the filter was applied?


Changing the wrapper tag for inserted elements in Cocoon for Rails


I was wondering if it were at all possible to change the element type of the wrapper for newly inserted inputs. Going through the docs I was unable to find a way in doing so.

Simply put I need to change nested-fields div into a table and change the inserted inputs, that have a class of input into trs with the inputs wrapped inside tds. This would look something like this:

<table class="track-form nested-fields">
  <tr><td><%= f.input :disc %></td></tr>
  <tr><td><%= f.input :number %></td></tr>
  <tr><td><%= f.input :name %></td></tr>
</table>

Unfortunately manually changing these tags is only ignored when the views are rendered. Here's what the view code currently looks like without the table elements added:

Form View

<%= simple_form_for(@album) do |f| %>
  <div class="form-inputs">
    ...
  </div>

  <div class="form-inputs">
    <%= f.simple_fields_for :tracks, tag: "table" do |track| %>
      <%= render 'track_fields', :f => track %>
    <% end %>

    <div id='links'>
      <%= link_to_add_association 'Add a Track', f, :tracks %>
    </div>
  </div>

Partial

<div class="track-form nested-fields">
  <%= f.input :disc %>
  <%= f.input :number %>
  <%= f.input :name %>

  <%= link_to_remove_association "remove track", f %>
</div>


longest palindrome in Ruby on Rails


Write a method that takes in a string of lowercase letters (no uppercase letters, no repeats). Consider the substrings of the string: consecutive sequences of letters contained inside the string. Find the longest such string of letters that is a palindrome.

Based on local method Palindrome?(string), I implemented longest-palindrome(string) as below with test cases:

def palindrome?(string)
  i = 0
  while i < string.length
    if string[i] != string[(string.length - 1) - i]
      return false
    end

    i += 1
  end

  return true
end

def longest_palindrome(string)
  dix = 0
  lstr = ""
  lstrc = nil
  while dix < string.length
    dix2 = 1
    while dix2 < string.length
      str = string.slice(dix,dix2)
      count = str.length
      if palindrome?(str)
        if lstrc == nil || lstrc < count
          lstr = str
          lstrc = count
        end
      end
      dix2 += 1
    end
    dix += 1
  end
  puts(lstr)
  return lstr
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts(
  'longest_palindrome("abcbd") == "bcb": ' +
  (longest_palindrome('abcbd') == 'bcb').to_s
)
puts(
  'longest_palindrome("abba") == "abba": ' +
  (longest_palindrome('abba') == 'abba').to_s
)
puts(
  'longest_palindrome("abcbdeffe") == "effe": ' +
  (longest_palindrome('abcbdeffe') == 'effe').to_s
)

Test results as below:

bcb                                                                                                                                                                                    
longest_palindrome("abcbd") == "bcb": true                                                                                                                                             
bb                                                                                                                                                                                     
longest_palindrome("abba") == "abba": false                                                                                                                                            
effe                                                                                                                                                                                   
longest_palindrome("abcbdeffe") == "effe": true  

Why did the second test failed?


Getting 403 (Forbidden) when trying to use CORS


I have a Spring websocket application that I want to access from another client.

I am using sockjs to do this.

When connection to http://localhost:8080/hello/info is attempted to open, I get a 403 (forbidden) error.

Here is my CORS conf in Spring:

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD, PATCH");
        response.setHeader("Access-Control-Allow-Headers",
                        "Origin, Content-Type, Accept, Cookie, Connection, Accept-Encoding, Accept-Language, Content-Length, Host, Referer, User-Agent");

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

If I try to use the socket from the page that Spring it self server, it works without problems. But when I do it from another client that uses that same Angular code that I have in Spring, it fails with the error above.

Here is the comparison of Request headers:

Working header:

GET /hello/info HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36
Accept: */*
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: remember_token=Q9M8fpJa13SsrXJOUDwVAg; _test1_session=N0wvOWV5cTU3VWd2TEs0SnZ2RkVqQ0lzN2tkbndzWmlodVl0VVl5eFdsR1FvYURKMEV0cFFsU2RpK2ZiVTF6ZHZLdFJnSUY0Ukl1Nloxd29QQlNFTmFBT2ZjbVA4M1ZzUEZubDZHSWFRTjhidVlTa3JoZE9MbEhBRGg5SmhmandRWkxNSXQ1cXFLb3ZRTXFLLzZGZGp3PT0tLXZ3czlJLzZxUjloR0EwcHlrdVVwc2c9PQ%3D%3D--c152b026e7859d5e8a5e8f260b66b33a6921f3b7; _harjutus_session=eVlEeU1nWjc4QjZhM0M4bEZQQ0FtVEp6UnFCYVkzUld1bVNDMVpTK1M2SmVjMEpQZlBSWWQ0YUxLczNZeGs5cGVJbWMybWxpN0lzKzBlRGJsR1JCVnQyN21ZWWZLMDJpZU1ENHE2VlJUcVFSdnU1aUVNOUpCOW5Cdyt2QSt0K2JrcHIzME56ZURlbTBtYmlTSlozcWpYY1FLMVlhMlVFWEp3WExNUHA1azdkWFpBY3NxQnJYeC90ZTJzR0NFa2VpYnNRcnp3c0ZOTVVmUDU4N2I4Zy92SHJMTDludVJYTkJtU3E2T0lGUFUwcEQrREtUUmtsdGdkWXVRR2lvN3pXMi0tTVB3WFB2M0NURDQvZlFwbm5UWEZqUT09--5e23d496aa3ecad4f5e7343ba8e326f18304844b

Not working header:

GET /hello/info HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36
Accept: */*
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4

Is the problem with the cookie header?

I did this the problematic client but nothing changed. But it should not matter also as both my Spring application and the Ruby on Rails application have exactly the same Angular code that is used to connect to the websocket.

app.config([
    '$httpProvider', function($httpProvider) {

        $httpProvider.defaults.withCredentials = true;

    }
]);


Gibbon API does not error, but does not subscribe


This is a strange one. I've had a working MailChimp, Gibbon, RoR app going for a couple of years now, and I went to go use part of my app this week and realized that the integration was no longer working. I am not receiving any errors, and some basic testing shows that the exception section of the code is never called.

Here is the code I am using:

begin
  gb = Gibbon::API.new(mailchimp_api_key)
  gb.lists.subscribe( id: mailchimp_list_id, email: {email: email} )
rescue Gibbon::MailChimpError => e
  logger.error "Mailchimp threw an error. The code is: #{e.code}, with message: #{e.message}"
end

Some code edited for readability, but assume that the variables are defined and no errors are thrown.

What I'm looking for is some debugging help. I can't seem to find a way to debug the integration to know if there is something silently failing or not. Does anyone have any tips for debugging this outside of trying to catch a raised exception?


Logging exceptions to log file in Ruby on Rails


I'm using log4jRuby to log the errors in my Rails application. Normally in development, any exceptions raised in the application will be directly displayed on the page. In production I set config.consider_all_requests_local = true in my enviorments/production.rb file. So that the users wont see any ugly exceptions. The page only shows a 500 server error when an exception occurs in production. I except the logs for the exception to be shown in my log files, but it doesn't. Now it's becoming difficult to know the reason why an exception occurred on production. Is there any other configuration that I'd have to set to achieve the same?

Rails 4.0.3 version.


Wicked Gem use of after edit page


I have a user model and boat model. They are associated. The thing is, when user creates a boat, the #create action redirects user to #edit page. In #edit page I have a long form that I want to use for wicked. Every video I watched, they used wicked gem after #create action. So I do not know if I can use it for the edit page. I have tried but encounter with an error.

boat_steps controller

 class BoatStepsController < ApplicationController
        include Wicked::Wizard

        steps :pricing, :description, :picture

        def show
            @boat = current_user.boats
            render_wizard
        end
    end

Boats controller

class BoatsController < ApplicationController
  before_action :logged_in_user, only: [:new, :show, :edit, :update]

  def new
    @boat = Boat.new
  end

  def create
   @boat = current_user.boats.new(boat_params) if logged_in?
    if @boat.save
      #flash[:success] = "Continue from here"
      render 'edit'
    else
      render 'new' 
    end
  end

  def show
    @boat = Boat.find(params[:id])

  end


  def edit
    @boat = Boat.find(params[:id])
  end


  def update
     @boat = Boat.find(params[:id])
    if @boat.update_attributes(boat_params)
      flash[:success] = "The Boat Saved"
      redirect_to boat_steps_path(@boat)
    else
      render 'edit'
    end
  end


  def update_years
  # updates year and model based on brand selected
  brand = Brand.find_by_name(params[:brand_name])
  # map to name and id for use in our options_for_select
  @years = brand.years.map{|a| [a.name, a.name]}.insert(0, "Select a Year") #use a.name here instead of a.id
  @models   = brand.models.map{|s| [s.name, s.name]}.insert(0, "Select a Model")#use s.name here instead of s.id
  end

  def update_models
  # updates model based on year selected
  year = Year.find_by_name(params[:year_name])
  @models = year.models.map{|s| [s.name, s.name]}.insert(0, "Select a Model") #use s.name here instead of s.id
  end



private

    def boat_params
      params.require(:boat).permit(:brand, :year, :model, :captained, :boat_type, :daily_price, :boat_length, :listing_tagline, :listing_description, :boat_category, :hull_material, :mast_material)
    end


end

The edit page works fine. Then when I click next to get the pricing step I get error, it might because of the boat_steps controller' s #show action or the from in the pricing.html.erb. But I could not find a solution. Here is the pricing.html.erb

<h2>Pricing</h2>

<%= form_for @boat, url: wizard_path do |f| %> <!-- HERE PROBLEM-->
      <%= f.radio_button(:captained, "Captained") %>
      <%= f.label(:captained_captained, "Captained") %>
      <%= f.radio_button(:captained, "Bareboat") %>
      <%= f.label(:captained_bareboat, "Bareboat") %>

      <%= f.label :daily_price, "Daily Price (TL)" %>
      <%= f.number_field :daily_price, placeholder: "Ex. 180.00", max: '1000.00',  class: 'form-control' %>

      <%= f.submit "Next", class: "btn btn-primary" %>
 <% end %>

So I get this error;

NoMethodError in BoatStepsController#show
undefined method `to_key' for #<Boat::ActiveRecord_Associations_CollectionProxy:0x007f85a5291fa8>

Or should I use wicked after #create action, instead of #edit action?


ActiveAdmin has_many form not saved if parent model is new and is NOT NULL in child model


I have two models, Room and Student. Room has_many Students. Student belongs_to Room.

I got an error Room can't be blank when I try to add Student to Room during creating a new Room.

My guess is that, upon submission, child object (student) is saved before parent object (room) is saved. Is there a way to bypass the order without remove the NOT NULL setting on room_id? Or my guess is wrong? Or even worse, I am doing it wrong?

# app/models/room.rb
class Room < ActiveRecord::Base
  validates :name, presence: true
  has_many :students

  accepts_nested_attributes_for :students
end



# app/models/student.rb
class Student < ActiveRecord::Base
  validates :name, presence: true

  belongs_to :room
  validates :room, presence: true # room_id is set to NOT NULL in database too.

end



# app/admin/room.rb
  form do |f|
    f.semantic_errors *f.object.errors.keys
    f.inputs "Room Details" do
      f.input :name

      f.has_many :students do |student|
        student.input :name
      end
    end

    f.actions
  end

  permit_params :name, students_attributes: [:name]


Bundle install: ERROR: Failed to build gem native extension


I'm currently working on a project using:

  • rvm 1.26.11
  • ruby 2.2.1p85

I tried to run bundle install but keep getting the following error:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

and, following:

An error occurred while installing nio4r (1.0.0), and Bundler cannot continue.
Make sure that `gem install nio4r -v '1.0.0'` succeeds before bundling.

When I try running gem install nio4r -v '1.0.0':

Building native extensions.  This could take a while...
ERROR: Error installing nio4r:
ERROR: Failed to build gem native extension.

When I try running bundle update:

Please make sure you have the correct access rights
and the repository exists.
Retrying git clone 'git@github.com:kshmir/requirejs-rails.git' ....*

Git error: command `git clone 'git@github.com:kshmir/requirejs-rails.git'....  has failed

When I try running bundle update nio4r:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension....
An error occurred while installing eventmachine (1.0.3), and Bundler cannot continue.
Make sure that `gem install eventmachine -v '1.0.3'` succeeds before bundling.

I tried that command too, to no result.

I also tried changing Ruby version:

rvm use 2.2.1 2.2.0 2.0.0 and running the commands above, but it doesn't change anything

Edit:

The output from running bundle install log:

Fetching gem metadata from rubygems....... Fetching version metadata from rubygems... Fetching dependency metadata from rubygems.. Using rake 10.2.2 Using i18n
0.7.0 Using multi_json 1.11.0 Using activesupport 3.2.17 Using builder 3.0.4 Using activemodel 3.2.17 Using erubis 2.7.0 Using journey 1.0.4 Using rack 1.4.5 Using rack-cache 1.2 Using rack-test 0.6.2 Using hike
1.2.3 Using tilt 1.4.1 Using sprockets 2.2.2 Using actionpack 3.2.17 Using mime-types 1.25.1 Using polyglot 0.3.4 Using treetop 1.4.15 Using mail 2.5.4 Using actionmailer 3.2.17 Using arbre 1.0.1 Using sass 3.2.19 Using thor 0.19.1 Using bourbon 3.1.8 Using bcrypt 3.1.7 Using bcrypt-ruby 3.1.5 Using orm_adapter 0.5.0 Using rack-ssl 1.3.4 Using json 1.8.1 Using rdoc 3.12.2 Using railties 3.2.17 Using atomic
1.1.15 Using thread_safe 0.2.0 Using warden 1.2.3 Using devise 3.2.3 Using formtastic 2.2.1 Using has_scope 0.6.0.rc Using responders 1.0.0 Using inherited_resources 1.4.1 Using jquery-rails 2.3.0 Using kaminari 0.15.1 Using arel 3.0.3 Using tzinfo 0.3.39 Using activerecord 3.2.17 Using polyamorous 0.5.0 Using meta_search 1.1.3 Using activeresource 3.2.17 Using bundler 1.8.4 Using rails 3.2.17 Using activeadmin 0.6.2 Using rgeo 0.3.20 Using rgeo-activerecord
0.5.0 Using activerecord-postgis-adapter 0.6.5 Using addressable 2.3.5 Using airbrake 3.1.16 Using descendants_tracker 0.0.3 Using ice_nine
0.11.0 Using axiom-types 0.0.5 Using coderay 1.1.0 Using better_errors 1.1.0 Using debug_inspector 0.0.2 Using binding_of_caller 0.7.2 Using bootstrap-datepicker-rails 1.1.1.8 Using bootstrap-sass 3.1.1.0 Using browser 0.8.0 Using columnize 0.3.6 Using debugger-linecache 1.2.0 Using byebug 2.7.0 Using cancan 1.6.10 Using highline 1.6.21 Using net-ssh 2.8.0 Using net-scp 1.1.2 Using net-sftp 2.1.2 Using net-ssh-gateway 1.2.0 Using capistrano 2.15.5 Using mini_portile 0.5.2 Using nokogiri 1.6.1 Using ffi 1.9.3 Using childprocess 0.5.1 Using rubyzip 1.1.0 Using websocket 1.0.7 Using selenium-webdriver 2.40.0 Using xpath 1.0.0 Using capybara 2.0.2 Using carrierwave 0.10.0 Using carrierwave_backgrounder 0.3.0 Using hitimes 1.2.2 Using timers 4.0.1 Using celluloid 0.16.0

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /home/adrian/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20150424-28432-11y95op.rb extconf.rb  checking for rb_thread_blocking_region()... no checking for sys/select.h... yes checking for poll.h... yes checking for sys/epoll.h... yes checking for sys/event.h... no checking for port.h... no checking for sys/resource.h... yes creating Makefile

make "DESTDIR=" clean

make "DESTDIR=" compiling selector.c In file included from nio4r.h:10:0,
                 from selector.c:6: /home/adrian/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" [-Wcpp] 
#warning use "ruby/io.h" instead of "rubyio.h"   ^ In file included from selector.c:7:0: /home/adrian/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubysig.h:14:2: warning: #warning rubysig.h is obsolete [-Wcpp]  #warning rubysig.h is obsolete   ^ selector.c: In function ‘NIO_Selector_allocate’: selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
     ev_init(&selector->timer, NIO_Selector_timeout_callback);
     ^ selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
     ev_io_init(&selector->wakeup, NIO_Selector_wakeup_callback, selector->wakeup_reader, EV_READ);
     ^ selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c: In function ‘NIO_Selector_synchronize’: selector.c:159:11: warning: variable ‘current_thread’ set but not used [-Wunused-but-set-variable]
     VALUE current_thread, lock_holder, lock;
           ^ selector.c: In function ‘NIO_Selector_deregister_synchronized’: selector.c:241:11: warning: unused variable ‘monitor_args’ [-Wunused-variable]
     VALUE monitor_args[3];
           ^ selector.c:240:21: warning: unused variable ‘interests’ [-Wunused-variable]
     VALUE self, io, interests, selectables, monitor;
                     ^ selector.c: In function ‘NIO_Selector_select’: selector.c:268:20: warning: unused variable ‘array’ [-Wunused-variable]
     VALUE timeout, array;
                    ^ selector.c: In function ‘NIO_Selector_select_synchronized’: selector.c:286:9: warning: unused variable ‘i’ [-Wunused-variable]
     int i, ready;
         ^ selector.c: In function ‘NIO_Selector_run’: selector.c:326:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     ev_tstamp started_at = ev_now(selector->ev_loop);
     ^ selector.c:341:9: error: ‘TRAP_BEG’ undeclared (first use in this function)
         TRAP_BEG;
         ^ selector.c:341:9: note: each undeclared identifier is reported only once for each function it appears in selector.c:343:9: error: ‘TRAP_END’ undeclared (first use in this function)
         TRAP_END;
         ^ selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
         ev_timer_init(&selector->timer, NIO_Selector_timeout_callback, BUSYWAIT_INTERVAL, BUSYWAIT_INTERVAL);
         ^ selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c: In function ‘NIO_Selector_close’: selector.c:391:5: warning: passing argument 2 of ‘NIO_Selector_synchronize’ from incompatible pointer type [enabled by default]
     return NIO_Selector_synchronize(self, NIO_Selector_close_synchronized, self);
     ^ selector.c:157:14: note: expected ‘VALUE (*)(VALUE *)’ but argument is of type ‘VALUE (*)(VALUE)’  static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE
*args)
              ^ selector.c:391:5: warning: passing argument 3 of ‘NIO_Selector_synchronize’ makes pointer from integer without a cast [enabled by default]
     return NIO_Selector_synchronize(self, NIO_Selector_close_synchronized, self);
     ^ selector.c:157:14: note: expected ‘VALUE *’ but argument is of type ‘VALUE’  static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args)
              ^ selector.c: In function ‘NIO_Selector_closed’: selector.c:407:5: warning: passing argument 2 of ‘NIO_Selector_synchronize’ from incompatible pointer type [enabled by default]
     return NIO_Selector_synchronize(self, NIO_Selector_closed_synchronized, self);
     ^ selector.c:157:14: note: expected ‘VALUE (*)(VALUE *)’ but argument is of type ‘VALUE (*)(VALUE)’  static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE
*args)
              ^ selector.c:407:5: warning: passing argument 3 of ‘NIO_Selector_synchronize’ makes pointer from integer without a cast [enabled by default]
     return NIO_Selector_synchronize(self, NIO_Selector_closed_synchronized, self);
     ^ selector.c:157:14: note: expected ‘VALUE *’ but argument is of type ‘VALUE’  static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args)
              ^ selector.c: In function ‘NIO_Selector_wakeup’: selector.c:384:10: warning: ignoring return value of ‘write’, declared with attribute warn_unused_result [-Wunused-result]
     write(selector->wakeup_writer, "\0", 1);
          ^ make: *** [selector.o] Error 1

make failed, exit code 2

Gem files will remain installed in /home/adrian/.rvm/gems/ruby-2.2.1/gems/nio4r-1.0.0 for inspection. Results logged to /home/adrian/.rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/nio4r-1.0.0/gem_make.out An error occurred while installing nio4r (1.0.0), and Bundler cannot continue. Make sure that `gem install nio4r -v '1.0.0'` succeeds before bundling.


Save a blob object with paperclip


I have a data uri which I want to upload to the server and store it as a paperclip image attachment. So I used the info on this link to convert the data uri into a blob and then used FormData to upload it to the server. My coffeescript file looks like this

dataURLtoBlob = (dataURL) ->
  binary = atob dataURL.split(',')[1]
  array = []
  i = 0
  while i < binary.length
    array.push binary.charCodeAt(i)
    i++
  return new Blob [new Uint8Array(array)], {type: 'image/png'}

file = dataURLtoBlob(imageSrc)
fd = new FormData()
fd.append "image", file
$.ajax({
   url: "/posts",
   type: "POST",
   data: fd,
   processData: false,
   contentType: false,
});

And this is the create action in my controller

image = params[:image]
name = SecureRandom.hex + "png"
File.open("#{Rails.root}/public/uploads/#{name}", 'wb') do |f|
  f.write(image.read)
end

This works perfectly for storing the image on the server. But how do I integrate it with paperclip, i.e. to generate thumbnails, urls for these images? Thanks in advance.


Requiring "RMagick" is deprecated. Use "rmagick" instead.FactoryGirl


When I create an object via FactoryGirl and Faker, shell show me an error

[1] pry(main)> FactoryGirl.create(:company)
[DEPRECATION] requiring "RMagick" is deprecated. Use "rmagick" instead

but when I create object in development db - it's ok

there is factory

  factory :company do
    title Faker::Company.name
    image Faker::Avatar.image("my-own-slug", "200x200")
  end 

how fix?


How can I change my .xls.erb file to create a new sheet for each row?


I am following the RailsCast tutorial for Exporting CSV and Excel. My goal is to export to excel. Everything is working fine except that I would like each Product to have its on sheet. Below is the code per the tutorial and then my attempts at adjusting for my needs.

/config/application.rb

require File.expand_path('../boot', __FILE__)

require 'csv'
require 'rails/all'

/config/initializers/mime_types.rb

Mime::Type.register "application/xls", :xls

/app/models/product.rb

class Product < ActiveRecord::Base
  attr_accessible :name, :price, :released_on

  def self.to_csv(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |product|
        csv << product.attributes.values_at(*column_names)
      end
    end
  end
end

app/controllers/products.rb

class ProductsController < ApplicationController
  def index
    @products = Product.order(:name)
    respond_to do |format|
      format.html
      format.csv { send_data @products.to_csv }
      format.xls
    end
  end
end

/app/views/products/index.xls.erb

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://ift.tt/qQdaDR">
  <Worksheet ss:Name="Sheet1">
    <Table>
      <Row>
        <Cell><Data ss:Type="String">ID</Data></Cell>
        <Cell><Data ss:Type="String">Name</Data></Cell>
        <Cell><Data ss:Type="String">Release Date</Data></Cell>
        <Cell><Data ss:Type="String">Price</Data></Cell>
      </Row>
    <% @products.each do |product| %>
      <Row>
        <Cell><Data ss:Type="Number"><%= product.id %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.name %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.released_on %></Data></Cell>
        <Cell><Data ss:Type="Number"><%= product.price %></Data></Cell>
      </Row>
    <% end %>
    </Table>
  </Worksheet>
</Workbook>

All of that works to create an excel sheet with a column of Products and other columns for the attributes. As an attempt to create individual worksheets for each Product, I iterated through Products above the element in my .xls.erb. This led to the excel file being unreadable though.

/app/views/products/index.xls.erb

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://ift.tt/qQdaDR">
 <% @products.each do |product| %>
  <Worksheet ss:Name="Sheet1">
    <Table>
      <Row>
        <Cell><Data ss:Type="String">ID</Data></Cell>
        <Cell><Data ss:Type="String">Name</Data></Cell>
        <Cell><Data ss:Type="String">Release Date</Data></Cell>
        <Cell><Data ss:Type="String">Price</Data></Cell>
      </Row>
      <Row>
        <Cell><Data ss:Type="Number"><%= product.id %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.name %></Data></Cell>
        <Cell><Data ss:Type="String"><%= product.released_on %></Data></Cell>
        <Cell><Data ss:Type="Number"><%= product.price %></Data></Cell>
      </Row>
    </Table>
  </Worksheet>
 <% end %>
</Workbook>

How can I change my .xls.erb file to create a new sheet for each Product row?


Changing a wrapper tag in SimpleForm


I've read the docs on how to customize wrapper's globally in SimpleForm but what I'd like to do is change the wrapper specially for one view and the partial inside of it. Right now the partial is wrapped in a div with the class name nested-fields.

With the use of cocoon I'm also dynamically inserting new inputs that are also wrapped in divs.

Simply put I need to change nested-fields div into a table and change the inserted inputs, that have a class of input into trs with the inputs wrapped inside tds. This would look something like this:

<table class="track-form nested-fields">
  <tr><td><%= f.input :disc %></td></tr>
  <tr><td><%= f.input :number %></td></tr>
  <tr><td><%= f.input :name %></td></tr>
</table>

Unfortunately manually changing these tags is only ignored when the views are rendered. Here's what the view code currently looks like without the table elements added:

Form View

<%= simple_form_for(@album) do |f| %>
  <div class="form-inputs">
    ...
  </div>

  <div class="form-inputs">
    <%= f.simple_fields_for :tracks, tag: "table" do |track| %>
      <%= render 'track_fields', :f => track %>
    <% end %>

    <div id='links'>
      <%= link_to_add_association 'Add a Track', f, :tracks %>
    </div>
  </div>

Partial

<div class="track-form nested-fields">
  <%= f.input :disc %>
  <%= f.input :number %>
  <%= f.input :name %>

  <%= link_to_remove_association "remove track", f %>
</div>


Rails (asset pipeline) and jquery.validationEngine custom rule


I have a custom jquery.validationEngine Ajax call that I can get working by manually creating a file called jquery.validationEngine-en.js, copying in the plugins code and adding my custom rule (see below).

From what I can gather, this results in the file of the same name pulled in via //= require jquery.validationEngine-en being replaced by my custom file.

I'm wondering is this the best way to do this? Is there a way to add custom rules to the //= require jquery.validationEngine-en in application.js file without having to create my own?

I hope I've explained that properly.