mercredi 31 janvier 2018

Ruby on Rails Calling Object Stylesheet Error

First-time post. I'm having trouble referencing a stylesheet with Ruby on Rails for my Web Dev 1 class. I've found similar posts both here:

https://www.pixelstech.net/article/1476434897-Resolve-stylesheet_link_tag-fails-to-work-in-Ruby-on-Rails

and

TypeError: Object doesn't support this property or method

but my code doesn't seem to change, regardless of whether I change anything in application.html.erb or adding coffee-source to the gem. I still get an error message, and when I tried the workaround it's as if the code hasn't changed at all:

https://imgur.com/a/iqHf7

I'm sure this is quite a basic issue, but I'm quite lost. Any ideas?

Thanks and have a great day!

How to access a created factory bot value in cucumber step definitions?

I m new to factory bot and cucumber, How to access a created record using factory_bot in step definition? test/factories.rb

FactoryBot.define do factory :signuser do email 'abcd1123@test.xyz' password 'test123' password_confirmation 'test123' end end

In console FactoryBot.create(:signuser)

features/test_step.rb

When (/^enter exists details for Register$/)do

I want to access email "abcd1123@test.xyz" and password "test123" here in textfield

end

mardi 30 janvier 2018

Rails file not working on webserver

http://dev.nexal.net/project/index.erb

I am new to ruby, and I am trying to get this file to work the same as on a website, as it would on my computer. Am I doing anything wrong?

lundi 29 janvier 2018

How to find/fix a "stackoverflow exception in /action_dispatch/middleware/reloader"?

I get this Exception sporadic on my production debian / rails 3.2.22.5

It feels that it has something to do with caching.

I have a "permission_checker" that is called width almost every call on the server. It checks permission of the object requested - going down all records/models till it finds the final owner of this object/record, and then decides:

when no owner found then 404
when owner found same as logged in user then process page
when owner found is the public owner then process page read only
else raise permission exception

so far so good

The code looks like that (the 'aaa' so on and level error just for debugging)

# some processing to find the owner
# id_val is a hash holding the result of this

logger.error "needed owner id :#{id_val}".yellow

logger.error "aaa".yellow
needed_owner_id=id_val[:person_id]
if needed_owner_id
    logger.error "bbb  #{needed_owner_id}".yellow
    needed_owner=Person.find(needed_owner_id)  #<----- here is the crash
    logger.error "ccc".yellow
    logger.error "needed owner id :#{needed_owner_id} (#{needed_owner.owner_type}".red.on_white
    logger.error "ddd".yellow
    logger.error "current person id :#{@current_person ? @current_person.id : nil}".red.on_white
else
    logger.error "no needed owner found"
end

# further processing

if i don't get the stackoverflow, the output looks like this:

Started GET "/ldc/order_forms/ec0a08a6-8525-4c6e-9056-d387e7ad3b9c/edit" 
Processing by Ldc::OrderFormsController#edit as HTML
  Parameters: {"id"=>"ec0a08a6-8525-4c6e-9056-d387e7ad3b9c"}
  LoginData Load (0.1ms)  SELECT `login_data`.* FROM `login_data` WHERE `login_data`.`id` = '083a684f-db0e-4c87-a44e-d434d3334289' LIMIT 1
  Ldc::Person Load (0.1ms)  SELECT `ldc_people`.* FROM `ldc_people` WHERE `ldc_people`.`ustate` = 'A' AND `ldc_people`.`login_data_id` = '083a684f-db0e-4c87-a44e-d434d3334289' LIMIT 1
check in: {:order_form_id=>"ec0a08a6-8525-4c6e-9056-d387e7ad3b9c", :person_id=>nil}
  Ldc::OrderForm Load (0.1ms)  SELECT `ldc_order_forms`.* FROM `ldc_order_forms` WHERE `ldc_order_forms`.`ustate` = 'A' AND `ldc_order_forms`.`id` = 'ec0a08a6-8525-4c6e-9056-d387e7ad3b9c' LIMIT 1
  CACHE (0.0ms)  SELECT `ldc_order_forms`.* FROM `ldc_order_forms` WHERE `ldc_order_forms`.`ustate` = 'A' AND `ldc_order_forms`.`id` = 'ec0a08a6-8525-4c6e-9056-d387e7ad3b9c' LIMIT 1
needed owner id :{:person_id=>"c7285c28-0906-4592-bbd7-3fbe164a337e"}
aaa
bbb  c7285c28-0906-4592-bbd7-3fbe164a337e
  Ldc::Person Load (0.1ms)  SELECT `ldc_people`.* FROM `ldc_people` WHERE `ldc_people`.`ustate` = 'A' AND `ldc_people`.`id` = 'c7285c28-0906-4592-bbd7-3fbe164a337e' LIMIT 1
ccc
needed owner id :c7285c28-0906-4592-bbd7-3fbe164a337e
ddd
current person id :c7285c28-0906-4592-bbd7-3fbe164a337e
--------- permission check done ---------

If it fails then its all the same until the crash:

check in: {:order_form_id=>"ec0a08a6-8525-4c6e-9056-d387e7ad3b9c", :person_id=>nil}
  Ldc::OrderForm Load (3.2ms)  SELECT `ldc_order_forms`.* FROM `ldc_order_forms` WHERE `ldc_order_forms`.`ustate` = 'A' AND `ldc_order_forms`.`id` = 'ec0a08a6-8525-4c6e-9056-d387e7ad3b9c' LIMIT 1
  CACHE (0.0ms)  SELECT `ldc_order_forms`.* FROM `ldc_order_forms` WHERE `ldc_order_forms`.`ustate` = 'A' AND `ldc_order_forms`.`id` = 'ec0a08a6-8525-4c6e-9056-d387e7ad3b9c' LIMIT 1
needed owner id :{:person_id=>"c7285c28-0906-4592-bbd7-3fbe164a337e"}
aaa
bbb  c7285c28-0906-4592-bbd7-3fbe164a337e
Completed 500 Internal Server Error in 223.8ms

SystemStackError (stack level too deep):
  actionpack (3.2.22.5) lib/action_dispatch/middleware/reloader.rb:70

The code for lib/action_dispatch/middleware/reloader.rb:70 is a raise:

def call(env)
  @validated = @condition.call
  prepare!
  response = @app.call(env)
  response[2] = ActionDispatch::BodyProxy.new(response[2]) { cleanup! }
  response
rescue Exception
  cleanup!
  raise
end

Any ideas what these lines do, so I can search further?

Rails reload dynamic routes on multiple instances/servers

How can we force Rails to reload_routes on multiple servers/instances?

We have a multi-tenant platform in Google App-Engine running on 5+ instances and we want all of our sites to define their own set of routes from the backend. Whenever we have a new site we currently have to restart all servers in order to be able to access the new routes.

We followed this guide but it does only work on a local environment and is not updating routes on all servers in production without restarting the servers.

Our route files look like this:

routes.rb

Frontend::Application.routes.draw do
  root 'home#index'
  ...
  DynamicRoutes.load
end

lib/dynamic_routes.rb

def self.load 
  Frontend::Application.routes.draw do
    Site.all.each do |site|
      site.routes.each do |custom_route|
       route_name = custom_route[0]
       route = custom_route[1]

       # write the route with the host constraint
       self.constraints(:host => site.hostname) do
         case route_name
         when :contact_form
           mapper.match "#{route}", to: 'contact_forms#new' as: "contact_#{site.id}"
         end
         ...
       end
     end
    end
  end
end

def self.reload
  Frontend::Application.reload_routes!     
end

after each update of routes or creation of a new site we are running DynamicRoutes::reload

gem install jekyll bundler fails with 'make' not recognized (windows)

i am trying to install jekyll bundler i got an error "'make' is not recognized as an internal or external command, operable program or batch file. make failed, exit code 1"

Console output:

>gem install jekyll bundler
Fetching: public_suffix-3.0.1.gem (100%)
Successfully installed public_suffix-3.0.1
Fetching: addressable-2.5.2.gem (100%)
Successfully installed addressable-2.5.2
Fetching: colorator-1.1.0.gem (100%)
Successfully installed colorator-1.1.0
Fetching: http_parser.rb-0.6.0.gem (100%)
Temporarily enhancing PATH for MSYS/MINGW...
Building native extensions.  This could take a while...
ERROR:  Error installing jekyll:
        ERROR: Failed to build gem native extension.

    current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser
C:/Ruby24-x64/bin/ruby.exe -r ./siteconf20180129-15308-13njafn.rb extconf.rb
creating Makefile

current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser
make "DESTDIR=" clean
'make' is not recognized as an internal or external command,
operable program or batch file.

current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser
make "DESTDIR="
'make' is not recognized as an internal or external command,
operable program or batch file.

make failed, exit code 1

Gem files will remain installed in C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/http_parser.rb-0.6.0 for inspection.
Results logged to C:/Ruby24-x64/lib/ruby/gems/2.4.0/extensions/x64-mingw32/2.4.0/http_parser.rb-0.6.0/gem_make.out
Fetching: bundler-1.16.1.gem (100%)
Successfully installed bundler-1.16.1
Parsing documentation for bundler-1.16.1
Installing ri documentation for bundler-1.16.1
Done installing documentation for bundler after 54 seconds
1 gem installed

Adding Optional Locale and Country to Rails Routes

In my application, I need to add /en|es/usa|eg to every GET route but not to be mandatory.

The first part is the locale name "en, es, ..etc", the second part is the country code "usa, eg, ..etc".

So for example, if I have:

/users/login

I can also have:

/en/usa/users/login
/es/eg/users/login

So both work together.

I tried to use scoped routes:

scope '/:locale/:country/', locale: /#{I18n.available_locales.join('|')}/, country: /#{Country::COUNTRY_CODES.join('|')}/ do

But I found this solution very error-prone, and it's so hard to decide which routes to add inside that scope.

So I tried a different approach:

In the routes.rb file:

get "/:locale/:country_code/(*all)" => redirect(CountryLocaleRedirector.new), constraints: SeoUrlConstraint.new

In the initializers I added this class:

class CountryLocaleRedirector
  def call(_params, request)
    path = request.path.split('/').reject(&:blank?)
    queries = request.query_string.split('&').reject(&:blank?).map{|x| x.split('=', -2)}.inject({}) do |r, s|
      r.merge!({s[0] => s[1]})
    end

    if path[0].in?(%w[en ar])
      queries[:locale] = path[0]
      path = path[1..-1]
    end

    if path[0].in?(%w[usa eg es fr])
      country = Country.find_by_country_code(path[0].upcase)
      path = path[1..-1]
      request.session[:country_id] = country.id if country.present?
    end

    "/#{path.join('/')}?#{queries.to_a.map{|x| x.join('=')}.join('&')}"
  end
end

And the constraint for the route (to make it work only when the URL has locals and country codes), which I added also to the initializers:

class SeoUrlConstraint
  def matches?(request)
    request.path.split('/').reject(&:blank?)[0].in?(%w[kw bh ae qa sa en ar])
  end
end

This is working perfectly, and when I do any GET request that has /en/usa/..., it works but removing that from the URL (because I do redirection), and set the appropriate locales and country.

My question: Is there a way that I can stick that /en/usa/ and not remove it? Even if with monkey patching or something?

dimanche 28 janvier 2018

Rails devise, find current_user by session_store key

We have a production system (main app) running on Rails with devise gem configured (using Redis session store)(session is enabled for all subdomain)

I need to build a custom authentication service for one our subdomain based microservice. For each request, this microservice will be calling our main app with the cookie value of rails session store key (which is configured in config/initializers/session_store.rb).

So the question is, can I find the user mapped to that cookie value (or session)? (Using Devise or Warden)

Ruby on Rails, View cannot find path for Collection routes

I added a collection routes which is POST in my routes

 resources: curated_items do
    collection do
      post 'duplicate'
    end
  end

but in my view cannot find path for this duplicate prefix.enter image description here enter image description here

samedi 27 janvier 2018

Rails 5 validate parameters based on current user

I have a Product model which belongs_to a Category. A User only has access to a few categories.

How do I validate when creating a Product, that the User has access to the category_id it is trying to assign?

Let's assume I have the list of allowed Categories in session[:category_ids].

In the controller I use strong parameters like so:

def product_params
  params.require(:product).permit(:name, :description, :category_id)
end

Is it possible to filter out values we dont have access to here? Or is there a better way to achieve this?

vendredi 26 janvier 2018

NoMethodError in Articles#new in form_for using Rails 4.2.5 tutorial

I am trying to complete the official Rails tutorial and on step 5.2. The instructions are to do a form_with, but i got an error, looked up this StackOverflow post: Rails form_with results in a NoMethodError. I changed the form_with to form_for like the answer said, and i get this error:

NoMethodError in Articles#new

Showing /home/ubuntu/workspace/app/views/articles/new.html.erb where line #2 raised:

undefined method 'model_name' for {:scope=>:article, :url=>"/articles", :local=>true}:Hash

Extracted source (around line #2):

1. <h1>New Article</h1>
2. <%= form_for scope: :article, url: articles_path, local: true do |form| %>
3.   <p>
4.     <%= form.label :title %><br>
5.     <%= form.text_field :title %>
6.   </p>

Rails.root: /home/ubuntu/workspace

app/views/articles/new.html.erb:2:in '_app_views_articles_new_html_erb__1707235537542743350_40377020'

I am using Cloud9, if it helps. Here is my code for the view and controller:
View:

<h1>New Article</h1>
<%= form_for scope: :article, url: articles_path, local: true do |form| %>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

Controller:

class ArticlesController < ApplicationController
  def new
  end

  def create
    render plain: params[:article].inspect
  end
end

Override method Ruby

I would like to override the method: authorize_endpoint_url from the Gem in a Rails application: https://github.com/AzureAD/omniauth-azure-activedirectory/blob/master/lib/omniauth/strategies/azure_activedirectory.rb

I tried to do it by adding a file to config/initializers/oauth.rb

With the code:

module OmniAuth
  module Strategies
    # A strategy for authentication against Azure Active Directory.
    class AzureActiveDirectory
      def request_phase
        debugger
        "www.hans.com"
      end
    end
  end
end

But this approach doesn't seem to work, nothing get's actually overwriten. What do I wrong? Thank you

jeudi 25 janvier 2018

¿Usando activerecord, qué tipo de query sería mas efectivo teniendo en cuenta 2 tablas en relación de uno a muchos?

Tengo un escenario con 2 tablas relacionadas y quiero imprimir en pantalla en una lista información de ambas tablas.

opción1.

@data = User.where(id: [array_users_ids]).includes(:products)

opción2.

@data = User.where(id: [array_users_ids]).joins(:products).select('users.*, products.name as product_name')

Ahora lo que ocurre con la opción1 es que genera en la consola una consulta sql por cada usuario con sus productos.

en cambio la opción2 se traduce en un solo sql ejecutado.

He leido que la forma correcta de hacerlo sería con la opción1 pero para mi no tiene sentido si la opción2 genera una sola consulta sql y me trae la información correcta.

undefined method when trying to send params from a controller to another

I'am having an issue in rails when i'am trying to send params from a controller to another controller when i use:

CarsControllers.new.create

I'am having this error:

undefined method `parameters’ for nil:NilClass

and the params that i'am sending go as null why i'am having this error ?

and i'am sorry i'am still new with ruby on rails

Can columns of a data table be sorted? not content of a column

Say I have a datatable DT, I have 4 columns a, b, c & d. I have four user u1,u2,u3 & u4. I want to show the se columns as per user like -

for u1 => a b c d
for u2 => b c d a
for u3 => c d a b
for u4 => d a b c

Actually I want a dynamic sorting for DT columns as per user preference.

I am using rails 3. Any help will be appreciated! Thanks

Ruby on rails issue regarding routes with root url (ror 3.2)

I asked something similar here but it does not really help me with my problem. I setup a new server and I use code from my old server. There, everything worked like charme. But now I have the following issues:

I want project.test.com to be the first page (index page of projects).

Rake routes

root                    /                     projects#index
projectorganizer GET    /website(.:format)    projects#index

But always when I try project.test.com I get a list in the browser of name/public which looks like this list in the browser. When I do project.test.com/projectorganizer it works and there is the index page.

I didn't change the routes. Here is a piece of the routes.rb

Name::Application.routes.draw do
  root to: 'projects#index'
  resources :participants
  resources :persons
  resources :projects do
     get :magic
  etc.

With the upper routes.rb the old system worked fine. But now it doesn't. Has anyone an idea why?

The suggestion in the other thread will lead to an immense work of changes in the code I guess because in some code there is root_url etc. which doesn't seem to work now as well.

Thank you in advance.

mercredi 24 janvier 2018

How to render a value from an .rb file into an .erb file

I don't have much experience with Ruby all I wan't to do is render a value that I declare in an .rb file in an .erb file.

In my .rb file I have this:

def abc()
  begin
     "aaaaa"
  end
end

In my .erb file I have this:

Hello <% abc %>

When I run the app I only see:

Hello

But I expect to see:

Hello aaaa

Anybody can give me a hand, I don't really know ruby at all. Also I have no idea if this is ruby or ruby on rails so sorry if the tag below is wrong.

mardi 23 janvier 2018

How to put a backslash before single quote in ruby on rails?

At ruby on rails, my string variable is;

str = "Jane's very good..."

When I typed below;

>> str = "Jane\'s very good..."

"Jane's very good..."


>> str = "Jane\\'s very good..."

"Jane\\'s very good..."


How to get str variable with single quote like "Jane\'s very good..."

lundi 22 janvier 2018

Update attributes without touching the database in Rails

I have a situation where I have an ActiveRecord::Relation object, where the relation's objects have some has_many associations. There is another piece of code that deletes the database rows associated with this relation that doesn't go through the relation, using delete_all. I know what the new state of the relation's associations is even without going to the database so I want to be able to set the object's attributes in this relation manually without touching the database again.

I found this article which mentions the write_attribute method. This works, but it looks like it has been deprecated, so I'd rather not use. It also mentions attributes= as a way of doing this without accessing the database. Is there something that can achieve the effect of write_attribute where I won't access the database when modifying a relation's attributes?

dimanche 21 janvier 2018

Rails 5 Could not find table ''

After setup the act_as_follower gem

and properly added the button_link on user view show and configure the routes and the controller

Rails spits out this error about did not find table ¨ and did not specify which table.

ActiveRecord::StatementInvalid in UsersController#follow Could not find table ''

just point to current_user.follow(@user) on users controller.

Someone have any idea about this issue?

def follow
  @user = User.friendly.find(params[:id])

    if current_user == @user
    flash[:error] = 'You cannot follow yourself.'
  else
  current_user.follow(@user)
end
end

samedi 20 janvier 2018

rails devise reset password token is replaced with user's email only in production

I use rails 3 and devise 3.0.3. My devise views and controllers are mostly default. Here is PasswordsController:

class PasswordsController < Devise::PasswordsController
  layout "application_new"

  def new
    flash.clear
    super
  end

  def create
    self.resource = resource_class.send_reset_password_instructions(resource_params)

    if successfully_sent?(resource)
      respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name))
    else
      flash[:notice] = t("errors.no_user")
      respond_with(resource)
    end
  end

  def update
    self.resource = resource_class.reset_password_by_token(resource_params)

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      sign_in(resource_name, resource)
      respond_with resource, location: after_resetting_password_path_for(resource)
    else
      flash[:notice] = resource.errors.full_messages
      respond_with(resource)
    end
  end
end


And here is edit password form:

= form_for resource, as: resource_name, url: password_path(resource_name), html: { method: :put } do |f|
  h2 = t('signup.password_recovery')
  = f.hidden_field :reset_password_token
  .form-group
    = f.label :password, t("forms.new_password_label")
    = f.password_field :password, required: true, class: "form-control"
  .form-group
    = f.label :password_confirmation, t("forms.password_confirmation_label")
    = f.password_field :password_confirmation, required: true, class: "form-control"
  = f.submit t('users.account.save'), class: 'btn btn-fill orange'


When I try to reset user's password, it works perfectly well in development. Which means, I get a letter with reset link, which contains reset password token in parameters and leads to edit password page with appropriate form and hidden field with aforementioned token in it.

In production, I get similar letter containing a reset link with reset password token in parameters (it is always right token I double checked it); however, when I open edit password page, I see user's email in hidden reset password token field instead of the token itself. I don't understand how it gets there. Any suggestions?

P.S. I've already seen this topic Rails 4 + Devise: Password Reset is always giving a "Token is invalid" error on the production server, but works fine locally. it isn't the case, because I get right token in parameters, the problem is that somehow I get user's email instead of the token in my form.

vendredi 19 janvier 2018

Loop through attributes in the custom validation method

I want to loop through attributes which are validated with custom validation method. I have model Post which has_many :languages and a model Language which belongs_to :post. In the languages table I have columns - id, post_id, language.

Post model:

class Post < ApplicationRecord
  has_many :languages

  accepts_nested_attributes_for :languages, reject_if: :all_blank
  validates_associated :languages
end

Language model:

class Language < ApplicationRecord

  validate :unique_languages?

  def unique_languages?
    #LOOP ATTRIBUTES
  end
end

IIn the Language model in the unique_languages? I want too loop through all language attributes of the post. This is posts_controller with strong params and logic for creating a post:

class PostsController < ApplicationController

  def new
    @post = Post.new
    @post.languages.build if @post.languages.empty?
  end

  def create
    @post = Post.new(post_params)
    @post.languages.build if @post.languages.empty?
    if @post.save
      redirect_to action: 'new'
    else
      render 'new'
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, languages_attributes: [:language])
  end
end

Ignoring gems because its extensions are not built

I installed the rails in my machine

ruby 2.3.1

rails 5.1.4

Ubuntu 16.04 os

After rails installation, When i check rails version rails -v It throws Ignoring "Some gems list" because its extensions are not built

Ignoring nokogiri-1.8.1 because its extensions are not built.  Try: gem pristine nokogiri --version 1.8.1
Ignoring bindex-0.5.0 because its extensions are not built.  Try: gem pristine bindex --version 0.5.0
Ignoring byebug-9.1.0 because its extensions are not built.  Try: gem pristine byebug --version 9.1.0
Ignoring curb-0.9.4 because its extensions are not built.  Try: gem pristine curb --version 0.9.4
Ignoring executable-hooks-1.3.2 because its extensions are not built.  Try: gem pristine executable-hooks --version 1.3.2
Ignoring ffi-1.9.18 because its extensions are not built.  Try: gem pristine ffi --version 1.9.18
Ignoring gem-wrappers-1.3.2 because its extensions are not built.  Try: gem pristine gem-wrappers --version 1.3.2
Ignoring gem-wrappers-1.2.7 because its extensions are not built.  Try: gem pristine gem-wrappers --version 1.2.7
Ignoring nio4r-2.2.0 because its extensions are not built.  Try: gem pristine nio4r --version 2.2.0
Ignoring pg-0.21.0 because its extensions are not built.  Try: gem pristine pg --version 0.21.0
Ignoring websocket-driver-0.6.5 because its extensions are not built.  Try: gem pristine websocket-driver --version 0.6.5
Rails 5.1.4

After new rails application created successfully When i run bundle install It throws errror message like:

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

New rails installation with error when entering url

We installed rails on a new server. When we try access the url we get redirected to ourstuff/public which is not desired. In ourstuff there is app, config, public etc.

When we try the usual url xyz.com/ourstuff like from our other systems we get this error

Routing Error

No route matches [GET] "/ourstuff"

Try running rake routes for more information on available routes. 

Does anyone have an idea why this is?

Thank you in adcvance.

jeudi 18 janvier 2018

LoadError: incompatible library version with nokogiri 1.6.8.1

I am working on quite old project which is running on old version of Ruby and Rails.

Ruby Version = 1.9.3p551

Rails verison = 3.1.10

So when i am trying to configure this project on new machine the it shows the error related to NOKOGIRI.

"LoadError: incompatible library version - /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri/nokogiri.so /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:32:in require' /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:32:inrescue in ' /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:28:in <top (required)>' /var/www/glo/config/application.rb:7:in' /var/www/glo/Rakefile:4:in <top (required)>' LoadError: cannot load such file -- nokogiri/2.3/nokogiri /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:30:inrequire' /home/global/.rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:30:in <top (required)>' /var/www/glo/config/application.rb:7:in' /var/www/glo/Rakefile:4:in `' (See full trace by running task with --trace) global@del1-lhp-N01167:/var/www/glo$ ruby -v ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux] "

I have tried many things but still this problem is not solved.

So please help me out from this.

Thanks

rails 3 production add caching to index page

I have a rails 3 app and wanted the index page to not take "time" when reloading the page.
I have added caches_page :index in the controller.rb file and @page_caching = true in the index function.
How can i make the index page update every 15mns the query and not take time to load the page in between that 15mns caching.

class HomeController < ApplicationController

caches_page :index

def index
    @page_caching = true    

/config/environments/production.rb
config.action_controller.perform_caching = true

Ruby REDIS with EX AND NX

I am trying to implement a locking in our rails application server.

REDIS.setnx works fine if I want to acquire a lock forever. But I want to acquire lock with expiry, basically I want the lock to expire after certain duration so that lock will be free to be acquired again.

From REDIS's set documentation, I see it is possible. http://ift.tt/2hsU2s5 "The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis."

How to implement this in ruby. Command :

REDIS = Redis.new(host: ENV['REDIS_HOST'], port: ENV['REDIS_PORT'])
REDIS.set "key", "value", "nx", "ex", 3600

throws error:

ArgumentError: wrong number of arguments (given 5, expected 2..3)

There is another way to do that, but it requires two REDIS calls.

if(REDIS.setnx "key", "value")
    REDIS.setex "key", 3600, "value"
end

This method is not preferred. I am looking to a way to acquire REDIS lock with single REDIS call in ruby. Basically "SET resource-name anystring NX EX max-lock-time" equivalent in ruby.

Thanks,

Anshul

mercredi 17 janvier 2018

Ruby scraping and access remote CSV

I am working on scraping the website by using Capybara + Poltergeist and access to remote csv(https). The actual scraping part after website login works but when I access to remote csv with open(url) method, I get 403 error. However when I type the url into browser, I can download the csv. Is there any additional authentication needed? I assume open(url) just works since the website login with Capybara + Poltergeist already happens.

The csv url: https://sample/csv?start_date=2018-01-15&end_date=2018-01-15

The ruby code:

csv_url = build_url "https://sample/csv", start_date: '2018-01-15', end_date: '2018-01-15'
csv = open(csv_url)

Response:

[httplog] Sending: GET http://sample:443/csv?start_date=2018-01-15&end_date=2018-01-15
[httplog] Status: 403
[httplog] Response: (not available yet) => "403 Forbidden"

UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ()

this is my static_pages_controller_test,

    require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test "should get home" do
    get static_pages_home_url
    assert_response :success
  end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end
end

Error:

StaticPagesControllerTest#test_should_get_home: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2018-01-17 05:49:27.300065', '2018-01-17 05:49:27.300065', 298486374)

and i have change user.yml as,

one:
email: test1@test.com

two:
email: test2@test.com

Error:

StaticPagesControllerTest#test_should_get_about: ActiveRecord::Fixture::FormatError: fixture key is not a hash: C:/Sites/IntenetChatSystem/test/fixtures/users.yml, keys: ["one", "email",I'mtwo"]

im getting confuse what should i do,pplz give some suggesstions

mardi 16 janvier 2018

Separate database credentials for each rails daemon

I'm running multiple worker processes each in their own daemon (with the rails-daemon gem) that should each have separate db roles / privileges (e.g. one should only be able to read table X, the other can write to X and Y), but it seems like Rails is set up to read the db credentials from one config/database.yml. How do I set up configure multiple db users in rails so that each worker uses its own credentials?

Google Drive and ActiveStorage

Any hint about Google Drive and ActiveStorage?

Is there a way to use ActiveStorage with the Google Drive user account?

I have no clue about this.

Is it feasible?

cucumber and cheese database returns server error

I`m trying to run the local app on windows from cucumber and cheese book and I get a server error.

Below is the terminal output:

F:\RM\puppies>rails s
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activesupport-3.2.11/lib/active_support/values/time_zone.rb:270: warning: circular argument
 reference - now
=> Booting WEBrick
=> Rails 3.2.11 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2018-01-15 10:57:48] INFO  WEBrick 1.3.1
[2018-01-15 10:57:48] INFO  ruby 2.4.2 (2017-09-14) [x64-mingw32]
[2018-01-15 10:57:48] INFO  WEBrick::HTTPServer#start: pid=10172 port=3000


Started GET "/" for 127.0.0.1 at 2018-01-15 10:58:09 +0200
Connecting to database specified by database.yml
Processing by AgencyController#index as HTML
  Rendered agency/index.html.erb within layouts/application (22.8ms)
Completed 500 Internal Server Error in 93ms


Started GET "/" for 127.0.0.1 at 2018-01-15 10:58:10 +0200
Processing by AgencyController#index as */*
  Rendered agency/index.html.erb within layouts/application (3.5ms)
Completed 500 Internal Server Error in 31ms

The entire project can be found here: http://ift.tt/2rbFfIq

I`ve tried with 2 ruby versions: 242 and 250.

Any help is much appreciated.

Also I have tried the solutions provided so far, my guess is it could be the setup I`m using.

Helper view with multiple blocks

I want to create a nice helper, which looks like following (easy example, I want to make it much more complicated):

# in my haml-file

-mywidget do |widget|
  -widget.header do
    %h1 header
  -widget.body do
    Lorem Ipsum 123123...
  -widget.footer do
    footertext
  AdditionalContentWithoutBlock

I tried to create my own helper class, but was not successfull so far.. Anybody has a small example or link on how to create such block attributes?

lundi 15 janvier 2018

Association not saving using form_for (cocoon gem)

Kind of new to rails so help is greatly appreciated.

I'm working on a rails-based app, with a few associations. A user has a diary, and a diary has many workout contents and many nutritional contents. Workout content class has many exercises, and nutritional content class has many meals. When building instances of the associations in rails console, it works. So I know my schema and classes are good, it's just that the data does not persist when submitted through a form. The issue is, when I fill out the information for workout content and exercises, the data persists. Same as when I enter for nutritional content. But when I enter fields for the meals attributes, the data does not persist.

My models are built as so:

class DiaryEntry < ApplicationRecord
 belongs_to :user
 has_many :workout_contents
 has_many :nutritional_contents
 has_many :exercises, through: :workout_contents
 has_many :meals, through: :nutritional_contents
 accepts_nested_attributes_for :exercises, reject_if: :all_blank, allow_destroy: true
 accepts_nested_attributes_for :meals, reject_if: :all_blank, allow_destroy: true
 accepts_nested_attributes_for :nutritional_contents, reject_if: :all_blank, allow_destroy: true
 accepts_nested_attributes_for :workout_contents, reject_if: :all_blank, allow_destroy: true

end

class WorkoutContent < ApplicationRecord
 belongs_to :diary_entry
 has_many :exercises
 accepts_nested_attributes_for :exercises, reject_if: :all_blank, allow_destroy: true

end

class NutritionalContent < ApplicationRecord
 belongs_to :diary_entry
 has_many :meals
accepts_nested_attributes_for :meals, reject_if: :all_blank, 

allow_destroy: true end

class Meal < ApplicationRecord
 belongs_to :nutritional_content
 validates :calories, :protein, :carbs, :fat, :numericality => { :only_integer => true }

end

class Exercise < ApplicationRecord
 validates :name, :length => { :minimum => 2 }
belongs_to :workout_content

end

Below are my forms:

Main form for new entry:

  <%= form_for @diary_entry, url: user_diary_entries_path(current_user) do |f| %>
   <div id='contents'>
     <%= f.fields_for :workout_contents, @diary_entry.workout_contents.build do |content| %>
  <% end %>
  </div>
  <div class='links'>
    <%= link_to_add_association 'Add Workout', f, :workout_contents, partial: 'workout_content_fields' %>
  </div>
  <h3>Add Nutrition Information to Diary</h3>
    <div id='contents'>
      <%= f.fields_for :workout_contents, @diary_entry.nutritional_contents.build do |content| %>
      <% end %>
    </div>
    <div class='links'>
      <%= link_to_add_association 'Add Meal', f, :nutritional_contents, partial: 'nutritional_content_fields' %>
    </div>
<%= f.submit 'Save Diary Entry' %>

workout content fields partial:

<div class='nested-fields'>
  <%= f.label :workout_name, value: "Workout Name"%>
  <%= f.text_field :workout_name%>
  <%= f.label :workout_type, value: "Workout Type"%>
  <%= f.text_field :workout_type%>
  <%= f.fields_for :exercises do |exercise| %>
  <%= render 'exercise_fields', :f => exercise %>
<% end %>
<div class='links'>
  <%= link_to_remove_association "remove workout", f %>
  <%= link_to_add_association 'Add exercise to workout', f, :exercises %>
</div>

Exercise fields partial:

<div class='nested-fields'>
  <%= f.label :name, value: "Exercise Name"%>
  <%= f.text_field :name%>
  <%= link_to_remove_association "remove exercise", f %>
</div>

nutritional content fields partial:

<div class='nested-fields'>
  <%= f.label :meal_type, value: "Meal Type"%>
  <%= f.select :meal_type, [ 'Breakfast','Lunch','Dinner', 'Snack' ], :prompt => 'Select One' %>
  <%= f.fields_for :meals do |meal| %>
  <%= render 'meal_fields', :f => meal %>
<% end %>
<div class='links'>
  <%= link_to_add_association 'Add nutritional details', f, :meals %>
  <%= link_to_remove_association "remove meal", f %>
</div>

Meals fields partial:

<div class='nested-fields'>
  <%= f.label :calories, value: "Calories"%>
  <%= f.text_field :calories%>
  <%= f.label :protein, value: "Protein"%>
  <%= f.text_field :protein%>
  <%= f.label :carbs, value: "Carbs"%>
  <%= f.text_field :carbs%>
  <%= f.label :fat, value: "Fat"%>
  <%= f.text_field :fat%>
  <%= link_to_remove_association "remove nutrition content", f %>

And lastly, in my DiaryEntiresController I have:

def new
 @diary_entry = DiaryEntry.new
end

def create
 @diary_entry = DiaryEntry.new(diary_params)
 @diary_entry.user_id = current_user.id
 @diary_entry.save
 redirect_to user_diary_entry_path(current_user, @diary_entry)
end

and:

  def diary_params
   params.require(:diary_entry).permit(:notes,
   workout_contents_attributes: [:id, :workout_name, :workout_type, :_destroy, exercises_attributes: [:id, :name, :_destroy]],
  nutritional_contents_attributes: [:id, :_destroy, :meal_type, meals_attributes: [:id, :protein, :carbs, :fat, :_destroy]])
 end

Again, adding workout_contents_attributes, exercises_attributes, nutritional_contents_attributes all work. It is only meals_attributes that is giving me trouble.

Thanks in advance!!

Find all Users that bought their car before they were 18

I want to find all Users that bought their car before they were 18.

I need a query like this:

User.includes(:car)
    .where(car: { bought_at < (user.birthday + 18.years)})

How can I write such an query in Rails 5 with Postgresql? Thank you

Nested ActiveRecord acces

I am trying to access nested ActiveRecord data in my Rails Project.
I want to acces all Devices in all Subnets of a single user
I would like to do something like this:

def index
    @user = User.find(params[:user_id])
    @subnets = @user.subnets.all
    @devices = @subnets.each.devices.order(sort_column+' '+sort_direction).search(params[:search])
    respond_to do |format|
      format.html
      format.csv { send_data Device.to_csv(@devices) }
    end
end

But of cause the @subnet.each.devices part does not work.

Is there a way I could do this without iterating and creating an array, since then I would not be able to use the order function anymore.

Validate uniqueness of a value with scope - Ruby on Rails 5

I have table posts with a model Post and table languages (columns - id, post_id, language) with a model Language. Post has many languages and Language belongs to a Post. In the post model I have:

has_many :languages
validates_associated :languages

Language model:

belongs_to :post
validates_uniqueness_of :language, scope: :post_id

language is the column in the table languages.

The language field is allowed in the posts_controller (strong parameters):

def post_params
    params.require(:post).permit(:languages_attributes => [:language], ...)

This is the view for the form for creating a post:

<%= form_for @post do |f| %>
    .....
    <%= f.fields_for :languages do |language| %>
        <%=language.select :language, ['english', 'italian', 'french', 'spanish'] %>
    <% end %>

This select element can be cloned up to 4 times via JS and user can add more than 1 language. The generated HTML for this select is:

<select name="post[languages_attributes][0][language]" id="post_languages_attributes_0_language">
    <option value="english">english</option>
    <option value="italian">italian</option>
    <option value="french">french</option>
    <option value="spanish">spanish</option>
</select>

When user clicks on the button and another select is created, it is with name post[languages_attributes][counter++][language] and everything works fine.

This is create post method:

@post= Post.new(post_params)
if @post.save
....

I want to validate uniqueness of the languages with scope of the current post (scope: :post_id) and every post to have only 1 time English language for the example. The post can have more than 1 languages.

I tried with validates_uniqueness_of :language, scope: :post_id, but if I add two times English (all lowercase), there is no error for this and the data is inserted to the tables.

How to validate uniqueness of the languages for a post with the scope of the current post ?

dimanche 14 janvier 2018

Merging multi-level hash in to a Single hash

I have a source hash:

a = {'1' => 'A', '2' => 'B', '3' => 'C', '4' => { '5' => 'D', '6' => 'E', '7' => { '8' => 'F', '9' => 'G' }}, '10' => {'11' => 'H'}}

I need to construct a method to make it a flat hash (single hash). I have seen ways at which we can merge 2 hashes (using deep_merge!) but I need to merge the above given hash. Please suggest a solution!

samedi 13 janvier 2018

Ruby on Rails Coursera Class Bug in Tests

I'm currently taking Coursera's free Ruby on Rails Introduction class. I'm working on the third assignment which contains creating a People class where you have some functionality like a search function.

I'm getting a weird error when I run rspec with their designed unit tests. I'm 99% sure the error is lying in the unit tests. Specifically, before I've even touched any files, I'm getting the following error:

        raise <<-EOS
        #{description} accessed in #{article} #{hook_expression} hook at:
          #{CallerFilter.first_non_rspec_line}

        `let` and `subject` declarations are not intended to be called
        in #{article} #{hook_expression} hook, as they exist to define state that
        is reset between each example, while #{hook_expression} exists to
        #{hook_intention}.
        EOS

      RuntimeError:
        let declaration `class` accessed in an `after(:context)` hook at:
          /Users/<username>/.rvm/gems/ruby-2.4.0/gems/rspec-core-3.7.1/exe/rspec:4:in `<top (required)>'

        `let` and `subject` declarations are not intended to be called
        in an `after(:context)` hook, as they exist to define state that
        is reset between each example, while `after(:context)` exists to
        cleanup state that is shared across examples in an example group.

For starters, I don't totally understand the syntax they're using to describe talking about their tests. Secondly, here is the raw testing file that the author's of the Coursera class wrote:

require 'rspec'
require 'rspec/its'
require_relative '../module2_lesson3_formative.rb'

describe "lesson3" do

  context "check results" do
    p1 = Person.new("Ivana", "Trump")
    p2 = Person.new("Eric", "Trump")
    p3 = Person.new("Melania", "Trump")
    p4 = Person.new("Marla", "Maples")

    it "unexpected search result" do
      expect(Person.search("Trump").size).to be == 3
    end
  end

  context "check instance properties" do
    subject(:john) { Person.new("Chris", "Christie") }

    it "missing first_name" do
      is_expected.to respond_to(:first_name)
    end

    it "missing last_name" do
      is_expected.to respond_to(:last_name)
    end

  end

  context "check class properties" do
    subject(:class) { Person }

    it "missing search" do
      is_expected.to respond_to(:search)
    end
  end
end

I am hoping that someone can explain to me the debugging information when I run rspec. I'm using RSpec 3.7 which I'm guessing is the problem, as indicated that it might be a versioning upgrade thing here. That would also explain the fact that the class's authors didn't intentionally push up bad code. What is the best way for me to fix this and why are lines like this:

subject(:john) { Person.new("Chris", "Christie") }

in bad form? Thanks so much! Really appreciate your time :)

vendredi 12 janvier 2018

sunpspot solr + rails: undefined methodprepare' for class Sunspot::Indexer'

I am new solr and trying to setup the dev environment of a rails application.

I am have already installed Java-7 and solr on ubuntu machine but when I try to start solr I get the below error

vagrant@precise64:~/myapp/scams$ rake sunspot:solr:start rake aborted! NameError: undefined methodprepare' for class Sunspot::Indexer' /home/vagrant/myapp/scams/config/initializers/sunspot_id.rb:2:inblock in ' /home/vagrant/myapp/scams/config/initializers/sunspot_id.rb:1:in module_eval' /home/vagrant/myapp/scams/config/initializers/sunspot_id.rb:1:in' /home/vagrant/.rvm/gems/ruby-2.2.7/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:i`

sunspot.yml:

 development:
     solr:
       hostname: localhost
       port: 8982
       log_level: INFO
       #path: /solr/development
       solr_home: solr
       # pid_dir: defaults to 'app/solr/pids/development'
       # bind_address: defaults to '0.0.0.0' which binds to every interface
    disabled: false # note that this is not indented within solr
   test:
    solr:
      hostname: localhost
      port: 8981
      log_level: WARNING

Sunpot_id.rb:

Sunspot::Indexer.module_eval do
  alias :old_prepare :prepare

  def prepare(model)
    document = old_prepare(model)
    if model.class == Resource
      document.fields_by_name(:resource_id_ss).first.value = document.fields_by_name(:id).first.value
      if !document.fields_by_name(:filename).blank? and !document.fields_by_name(:filename).first.blank?
        document.fields_by_name(:id).first.value = document.fields_by_name(:filename).first.value
      end
    end
    document
  end

It has been more than two days with the issue. Someone please help me with this.

Facing Hackers Attack in my Rails App hosted on AWS

I found some unauthorized access_log in our production.log file, where /proxy.php, /testproxy.php pages, /JBOSSServlet, /pp/anp/php type pages are hit too many times while our rails website page uses .html and .erb type pages.

How can I block those URLs into my rails app?

There is also a possibility that there is any unauthorized script running on my server, in this case how we find it and kill that processes.

I also try to use rack_attack gem to block the URLs which hits beyond the given limit, but I am not able to configure it correctly.

please help.

jeudi 11 janvier 2018

How can I display a custom error page with Ruby on Rails in any failure case?

I know that if an exception is raised in my main app, I can use the exceptions_app configuration attribute to serve a dynamic error page.

However, if this error page is dynamic, it might also fail. In my case, I'm sharing some of the display logic with the main app, and it happened that that logic was the source of the exception, and rendering the error page raised it again. My end users then saw the Passenger error page, which is all purple and weird and frightening.

How can I reliably display a custom error page to my users, possibly with a static page fallback?

Get all possible substrings and their count

I'm trying to get all possible substrings and their count in a hash. E.g.

 "abc" => { a: 1, b: 1, ab: 1, bc: 1}

For that I wrote the following code:

 def get_all(b)
     (0..(b.size-1)).to_a.combination(2).inject({}) { |h, g|
        s = b[g[0],g[1]]
        h[s] ? ( h[s] += 1) : ( h[s] = 1 )
        h 
      } 
 end

But somehow It does not work correctly, because for "abchh" It returns:

{"a"=>1, "ab"=>1, "abc"=>1, "abch"=>1, "bc"=>1, "bch"=>1, "bchh"=>1, "chh"=>2, "hh"=>1}

chh is in there twice, but I can't understand why. What do I wrong?

Thank you!

Database adapter seamless_database_pool not supported Rails error

Database adapter seamless_database_pool not supported. Use:\nForeigner::Adapter.register 'seamless_database_pool', 'path/to/adapter'

After update gem, I start getting Database adapter not supported.

After that my all rake task not working.

seamless_database_pool use for PostgreSQL.

Please give you input.

mercredi 10 janvier 2018

undefined method forget for nil in test file - RailsTutorial 9.12

I am new to rails so please forgive the following noob question and thanks in advance...

I am following the rails tutorial however, once I got to section 9.12 where we add the forget logic to sessions_helper.rb, I get the below error which is confusing to me since I see the forget method defined properly. The error occurs when trying to run the users_login_test.rb file

Error:
UsersLoginTest#test_login_with_valid_information_followed_by_logout:
NoMethodError: undefined method `forget' for nil:NilClass
    app/helpers/sessions_helper.rb:10:in `forget'
    app/helpers/sessions_helper.rb:42:in `log_out'
    app/controllers/sessions_controller.rb:18:in `destroy'
    test/integration/users_login_test.rb:34:in `block in <class:UsersLoginTest>'

Here is my Sessions Helper:

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end
end

Here is my user.rb:

    class User < ApplicationRecord
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end
end

Here is my failing testfile:

    require test_helper

class UsersLoginTest < ActionDispatch::IntegrationTest

 def setup
    @user = users(:michael)
 end

 test "login with invalid information" do
    get login_path
    assert_template 'sessions/new'
    post login_path, params: { session: { email: "", password: "" } }
    assert_template 'sessions/new'
    assert_not flash.empty?
    get root_path
    assert flash.empty?
  end

 test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                          password: 'password' } }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    # Simulate a user clicking logout in a second window.
    delete logout_path
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end
end

Are there any Bitcoin blockchain information parsing solutions for Ruby?

My target is to parse transaction information from bitcoin blockchain and export it to text files. Any suggested methods, library in Ruby environment would be highly appreciated.

Thanks in advance.

mardi 9 janvier 2018

How to bypass the form and pass information straight to the create action with a link_to in Rails

Setup

App has 3 models. A Member model, a Support model and an Involvement model. The member model keeps track of all of the users for my web app. The support model keeps track of the many different ways a user can support our organization. The Involvement model connects the other two models by keeping track of the member_id and support_id showing in which support areas the member is active.

Current Functionality

In a member's profile, they can look at a support tab which queries all the different areas that they can support from the support model. It then checks if there is a involvement that includes both their id and the id of that support area and states whether they are currently supporting or not.

Desired Outcome

I want to have a link that they can click on that will either create or delete an involvement. So, if they are currently supporting financially, it will state that they are and provide a link to stop supporting that way, which when clicked will delete the involvement record; and vise versa, if they are not supporting financially, a link will show to start supporting and that link will create the involvement record. (Ultimately I am going to integrate a toggle function which will allow a member to just toggle back and forth, but I need to work this out first.)

Question

Is there a way to send params via link_to to the 'create' or 'destroy' actions to bring about this functionality? Currently I am doing the following but get an error:

<%= 
    link_to "Start Supporting", 
    involvements_path(member_id: current_member.id, 
                      support_id: support_area.id), 
    method: :post 
%>

Error

ActionController::ParameterMissing in InvolvementsController#create
param is missing or the value is empty: involvement

When I do byebug, I get the following output for params:

(byebug) params
<ActionController::Parameters {"_method"=>"post", 
                               "member_id"=>"1", 
                               "support_id"=>"2",                                                                                                                                             
                               "controller"=>"involvements", 
                               "action"=>"create"} 
                                permitted: false>

So, it doesn't look like params is empty... is it not passing through the whitelist? Any ideas?

Code

rake routes

    involvements GET    /involvements(.:format)           involvements#index
                 POST   /involvements(.:format)           involvements#create
 new_involvement GET    /involvements/new(.:format)       involvements#new
edit_involvement GET    /involvements/:id/edit(.:format)  involvements#edit
     involvement GET    /involvements/:id(.:format)       involvements#show
                 PATCH  /involvements/:id(.:format)       involvements#update
                 PUT    /involvements/:id(.:format)       involvements#update
                 DELETE /involvements/:id(.:format)       involvements#destroy

app/models/involvement.rb

class Involvement < ApplicationRecord
  belongs_to :member
end

db/schema.rb

create_table "involvements", force: :cascade do |t|
   t.bigint "member_id"
   t.integer "support_id"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   t.index ["member_id"], name: "index_involvements_on_member_id"
end

app/views/profiles/show.html.erb

<% if @user == 'Owner' %>

  <% if @show_page == 'account' %>
    <%= render 'profile_account' %>
  <% elsif @show_page == 'main' %>
    <%= render 'profile_main', locals: { profile: @profile, 
                                         user: @user } %>
  <% elsif @show_page == 'support' %>
    <%= render 'profile_support', locals: { profile: @profile, 
                                            user: @user, 
                                            supports: @supports, 
                                            involvement: @involvements 
                                          } %>
  <% else %>
    <script type="text/javascript">
        window.location.href="<%= 
               member_profile_path(current_member.profile.u_name) 
        %>"
    </script>
  <% end %>

<% else %>
  <%= render 'profile_main', locals: { profile: @profile, 
                                       user: @user } %>
<% end %>

app/views/profiles/_profile_support.html.erb

<h1>This is the Support Page</h1>

<table style="width:50%">
  <tr>
    <th>Support Area</th>
    <th>Support Status</th>
    <th>Change Status</th>
  </tr>
  <% @supports.each do |support_area| %>
    <tr>  
      <th>
        <%= link_to support_area.title, support_page_path(support_area.title) %>
      </th>
      <th>
        <% @presence_check = Involvement.exists?(member_id: current_member.id, 
                                                 support_id: support_area.id) %>
        <% if @presence_check %>
          Supporting
        <% else %>
          Not Supporting
        <% end %>
      </th>
      <th>
        <%= link_to "Start Supporting", 
                    involvements_path(member_id: current_member.id, 
                                      support_id: support_area.id), 
                    method: :post %>
      </th>
    </tr>
  <% end %>
</table>

app/controllers/involvements_controller.rb

class InvolvementsController < ApplicationController
  before_action :set_involvement, only: [:show, :edit, :update, :destroy]

  def index
    @involvements = Involvement.all
  end

  def show
  end

  def new
    @involvement = Involvement.new
  end

  def edit
  end

  def create    
    @involvement = Involvement.new(involvement_params)
    # byebug
    respond_to do |format|
      if @involvement.save
        format.html { redirect_to @involvement, 
                      notice: 'Involvement was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @involvement.update(involvement_params)
        format.html { redirect_to @involvement, 
                      notice: 'Involvement was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @involvement.destroy
    respond_to do |format|
      format.html { redirect_to involvements_url, 
                    notice: 'Involvement was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_involvement
      @involvement = Involvement.find(params[:id])
    end

    # Never trust parameters from the scary internet, 
    # only allow the white list through.

    def involvement_params
      # byebug
      params.require(:involvement).permit(:member_id, :support_id)
    end
end

lundi 8 janvier 2018

act_as_commentable The scope body needs to be callable

After update to rails 5.1 and added the acts_as_commentable (4.0.2) This is due to the new rails?

someone is having the same issue with this gem?

The log shows

ArgumentError in PostsController#show

The scope body needs to be callable.

class Comment < ActiveRecord::Base

  include ActsAsCommentable::Comment

  belongs_to :commentable, :polymorphic => true

in the posts controller

 def show
    @post = Post.find(params[:id])
    @comment = @post.comments.new
  end

Permission denied @ unlink_internal, Rails 5 with CarrierWave

I have Ruby on Rails 5 with CarrierWave application. I have a model Post and a model 'Image'. Each post has only 1 video (it has column video in the table posts) and 0 or many images (table images). Model Post:

has_many :images

validates :video, presence: true
validates_associated :images

mount_uploader :video, VideoUploader

Model Image:

belongs_to :post
mount_uploader :image, ImageUploader

The video is required, but the images are not.

ImageUploader:

storage :file

def store_dir
  "posts/images"
end

def extension_whitelist
  %w(jpeg jpg)
end

def filename
  "#{secure_token}.jpg" if original_filename.present?
end

def remove_original_file(p)
  if self.version_name.nil?
    self.file.delete if self.file.exists?
  end
end
# GENERATE RANDOM NAME
def secure_token
  var = :"@#{mounted_as}_secure_token"
  model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end

VideoUploader:

storage :file

def store_dir
  "../videos/#{model.id}" # Not in the public directory
end

def extension_whitelist
  %w(mp4)
end

def filename
  "#{secure_token}.mp4" if original_filename.present?
end

# GENERATE RANDOM NAME
def secure_token
  var = :"@#{mounted_as}_secure_token"
  model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end

This a part of the view for form upload:

<%= form_for @post do |f| %>
.....
<%= f.fields_for :images do |i| %>
  <%= i.file_field :image, name: 'post[images_attributes][][image]' %>
  ......
  <%= i.file_field :image, name: 'post[images_attributes][][image]' %>
<% end %>

The input element for a video:

 <%=f.file_field :video, required: false, accept: '.mp4'%>

This posts_controller.rb:

def new
  @post= Performance.new
  @post.images.build
end

def create
  @post= Post.new(post_params)

  if @post.save 
    redirect_to action: :new
  else
    @post.images.build if @post.images.size == 0
    render :new
  end
end

private
def post_params
  params.require(:post).permit(:language, :name, :video, :slug, 
                                        :images_attributes => [:image])
end

There is no problem if I upload a post with 1 image. Everything works fine. The files (an image and a video) are uploaded and all data is in the database. The problem is when I try to upload more than 1 image. I see this error:

Permission denied @ unlink_internal - E:/project pah/public/uploads/tmp/1515418372-4328-0043-1599/video.mp4

I am using Windows 10. All the folders (public/*) are with all permissions (except special permissions) for all users.

The problem exists ONLY if I upload more than 1 image, but in some kind, it is related to the video.

After trying to upload and getting the error, I see that the temporary directory is created with the file (in this case E:/project pah/public/uploads/tmp/1515418372-4328-0043-1599/video.mp4) in it. Image temporary files exists, too and the files are in their directories (store_dir). In the database at the first time everything is inserted, but because of this error it rollback.

Rails 5 - How to sort has_many associations list?

In rails 5 and in postgresql, I want to sort a list based on created_at: :desc.

Model structure is like,

Review model has_many :comments and has_many :commented_users, :through=>:comments

In views, I want to display list of users based on created_at (DESC) date and this field is from comments table

Controller query is like,

review = Review.find_by_id(params[:id])
comments = review.commented_users

If I give order for review.commented_users then obviously it will sort User, how can I sort users based on Comment?

Please help me to solve this sorting issue and I am new to postgresql

dimanche 7 janvier 2018

Ruby on Rails ActiveRecord::PendingMigrationError

When I try to load my rails app on my local host I get an error telling me to resolve it by running rails db:migrate but when I try to run the command this is what I get

C:\Sites\CoolGuyGear>rails db:migrate == 20180108004216 AddDeviseToViews: migrating ================================= -- change_table(:views) rails aborted! StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email: ALTER TABLE "views" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in'

Caused by: ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "views" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in'

Caused by: SQLite3::SQLException: duplicate column name: email C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:7:in block in up' C:/Sites/CoolGuyGear/db/migrate/20180108004216_add_devise_to_views.rb:5:inup' bin/rails:4:in require' bin/rails:4:in' Tasks: TOP => db:migrate (See full trace by running task with --trace)

ID param not being sent to Controller when manually changing routes

I have looked through the other answers provided on StackOverflow, and none of them answered my question. Here is what is happening with my code.

Error

undefined method `update' for nil:NilClass

Problem: It looks like the param id is not being sent to the controller from the form as they show up as nil in the console using byebug.

console readout:

(byebug) params[:id]
nil
(byebug) @support
nil
(byebug) params[:title]
nil
(byebug) params[:support]
<ActionController::Parameters {"title"=>"Test", "subtitle"=>"testing", 
"website"=>"www.test.com", "type_of_support"=>"", "description"=>""}
permitted: false>
(byebug) params[:support][:id]
nil
(byebug) params[:support][:title]
"Test"

I do not believe that the problem is with the form as it is the same form partial used for the new/create action and the params are sent to the controller then and the object is created (though in that case there is no id, since it is generated when creating the object, not passed from the form).

You can see in my code below that the route for PATCH is just 'support' without the :id param. If I try to add that to the route, I get an error stating that there is no route matching 'support/'. So, I have to take away the :id param in the route for it to pass the information to the controller.

I am at a loss here. How do I pass the :id to the controller? How does rails do this? Before I manually change the routes, the automatic routes from resources :supports includes an :id param for the PATCH route and it works. What am I doing wrong that it won't allow me to add that to the route?

Code:

config/routes.rb

get    'support',          as: 'supports',     to: 'supports#index'
post   'support',                              to: 'supports#create'
get    'support/new',      as: 'new_support',  to: 'supports#new'
get    'support/:id/edit', as: 'edit_support', to: 'supports#edit'
get    'support/:title',   as: 'support_page', to: 'supports#show'
patch  'support/',                             to: 'supports#update'
put    'support/:id',                          to: 'supports#update'
delete 'supports/:id',                         to: 'supports#destroy'

Results this for rake routes:

supports     GET    /support(.:format)                supports#index
support      POST   /support(.:format)                supports#create
new_support  GET    /support/new(.:format)            supports#new
edit_support GET    /support/:id/edit(.:format)       supports#edit
support_page GET    /support/:title(.:format)         supports#show
             PATCH  /support(.:format)                supports#update
             PUT    /support/:id(.:format)            supports#update
             DELETE /supports/:id(.:format)           supports#destroy

app/controllers/supports_controllers.rb

class SupportsController < ApplicationController
  before_action :set_support_by_title, only: [:show]
  before_action :set_support_by_id,    only: [:edit, :update, :destroy]

  def index
    @supports = Support.all
  end

  def show
  end

  def new
    @support = Support.new
  end

  def edit
  end

  def create
    @support = Support.new(support_params)

    respond_to do |format|
      if @support.save
        format.html { redirect_to @support, 
                      notice: 'Support was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    # byebug
    respond_to do |format|
      if @support.update(support_params)
        format.html { redirect_to @support, 
                      notice: 'Support was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @support.destroy
    respond_to do |format|
      format.html { redirect_to supports_url, 
                    notice: 'Support was successfully destroyed.' }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_support_by_title
      @support = Support.find_by(title: params[:title])
      # byebug
    end

    def set_support_by_id
      @support = Support.find(params[:id])
      # byebug
    end

    # Never trust parameters from the scary internet, 
    # only allow the white list through.

    def support_params
      params.require(:support).permit(:title, 
                                      :subtitle, 
                                      :website, 
                                      :type_of_support, 
                                      :description)
    end
end

app/views/supports/edit.html.erb

<h1>Editing Support</h1>

<%= render 'form', support: @support %>

<%= link_to 'Show', support_page_path(@support.title) %> |
<%= link_to 'Back', supports_path %>

app/views/supports/_form.html.erb

<%= form_with(model: support, local: true) do |form| %>
  <% if support.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(support.errors.count, "error") %> 
          prohibited this support from being saved:
      </h2>

      <ul>
      <% support.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    Title: 
    <%= form.text_field :title, id: :support_title %>
  </div>

  <div class="field">
    Subtitle: 
    <%= form.text_field :subtitle, id: :support_subtitle %>
  </div>

  <div class="field">
    Website: 
    <%= form.text_field :website, id: :support_website %>
  </div>

  <div class="field">
    Type of Support: 
    <%= form.text_field :type_of_support, id: :support_type %>
  </div>

  <div class="field">
    Description: 
    <%= form.text_area :description, id: :support_description %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

samedi 6 janvier 2018

Trying to find a good way to chain scopes dynamically

I found this article on cleaning up chained scopes that would be great in a project I'm working on. However, some of my scopes have arguments. I can't think of a way to make this work with arguments. I tried string interpolation which I suspected wouldn't work and of course, didn't.

http://ift.tt/2ddyejQ

def self.send_chain(methods)
  methods.inject(self, :send)
end

$ methods = ["with_author", "pending_review", "draft", "flagged", "published", "with_website", "with_meta_title", "with_meta_description"]
$ Article.send_chain(methods)

How I can make admin, users, dashboard, and other settings

I need to develop admin dashboard for my further projects. I am junior and won't become a super ruby developer. can anyone help me or show me links.

Select expired and not expired values MySQL, Rails 5

I have Ruby on Rails 5 with MySQL app. I have table products and table subscription with the standard Rails 5 datetime column - created_at'.

The model Product has_many :subscriptions and the model Subscription belongs_to :product.

I want to select all subscriptions for a product that are created before for the example 1 day and all products that are created (for the example last 24 hours) in this way that I can use them like this - product.expired_subscriptions and product.active_subscriptions.

vendredi 5 janvier 2018

Fake URL for a page using rails

I am new to rails and I was wondering if it is possible to have a fake URL for a page that is there is a different package. For example if I have my main website running on xyz.com and on clicking a button it takes me to xyz-abc.com/page but I want the address in the url bar to show as xyz.com/page Can you please help me figure this out.

Is there a way to optimize this scope further?

I have this chained scope that produces the following sql. It important that it be ordered created_at desc and by comments with an actual comment, and the null values after that.

It's been optimized to use subqueries instead of joins and that has helped quite a bit, but still not enough.

Ultimately, the bottleneck is with trying to get null values at the end of the results.

This is a mysql db.

I have an index on comment and created_at together

SELECT `table_one`.*
FROM `table_one`
WHERE `table_one`.`status` = 'A'
  AND `table_one`.`table_two_id` IN
    (SELECT `table_two`.`id`
     FROM `table_two`
     WHERE `table_two`.`slug` IS NOT NULL
       AND `table_two`.`status` = 'R')
  AND `table_one`.`table_three_id` IN
    (SELECT `table_three`.`table_three_id`
     FROM `table_three`
     WHERE `table_three`.`status` = 'A'
       AND `table_three`.`table_four_id` IN
         (SELECT `table_four`.`id`
          FROM `table_four`
          WHERE `table_four`.`status` = 'A'
            AND `table_four`.`table_three_id` = 6))
ORDER BY CASE
             WHEN COMMENT IS NULL THEN 1
             ELSE 0
         END,
         table_one.created_at DESC
LIMIT 20
OFFSET 0

this is querying over a million rows and will take ~12 seconds. If I remove any attempt to get the NULLS last it will run reasonably quickly.

Can you see a wat to speed it up?

Rails add @ symbol on username after Signup

Is there a gem to add the @ symbol on username after create the user?

Or this is just a html data on the websites like twitter?

jeudi 4 janvier 2018

Ruby on Rails Rollback except a given model

I am running on Rails 3.2.22 and I can't get transaction/rollback working. This code should always print "WORLD" but actually, it will never work if raise is called. But according to Rails doc, it should always reach there. My question is - is there a way how to save @pb status into a database? If I decide to save the status before rollback, it will not save. If I save it after raise, it will not execute. Is there a way around that?

    @pb = ProgressBar.create(..)
    ..
    def import(user)
    Thread.new do
      ActiveRecord::Base.transaction do
        errs = operation(user)
        Rails.logger.info "HELLO"
        if errs.any?
          raise ActiveRecord::Rollback
        end
      end
      Rails.logger.info "WORLD"
      @pb.failed_import
    end
  end

mercredi 3 janvier 2018

Rails, Devise Pending Migrations Error

I tried installing devise for rails and it works fine on heroku but when I try to run my code on my local host for my dev environment I get this error saying "Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development"

I also get these errors when I try to migrate, C:\Sites\coolguygear>bundle exec rake db:migrate == 20180103100327 AddDeviseToUsers: migrating ================================= -- change_table(:users) rake aborted! StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup'

Caused by: ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup'

Caused by: SQLite3::SQLException: duplicate column name: email C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:7:in block in up' C:/Sites/coolguygear/db/migrate/20180103100327_add_devise_to_users.rb:5:inup' Tasks: TOP => db:migrate (See full trace by running task with --trace)

      # Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
  def check_pending!(connection = Base.connection)
    raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
  end

  def load_schema_if_pending!

mardi 2 janvier 2018

Rails listener for expired date

Is there such a thing as a listener in Ruby, or something similar? On example, how can I check if user date is expired and need to send email few days before?


Thanks on your time

Should I use hashes or ActiveRecord::Relations?

I'm really lacking some knowledge regarding efficiency/performance when working with massive amount of data.

I need to do some calculations on different models and then updating them. I was thinking:

Step I. Get the data from each table in hashes (hash_table_1, hash_table_2 etc) "plucking" the active record relations and then map it in a hash

Step II. Do calculations and change the values in the hashes (iterate over hashes, searching ids in hashes)

Step III. Updating data with Table_1.update(hash_table_1), Table_2.update(hash_table_2) etc. OR use raw SQL to update

Should I be using ActiveRecord::Relations instead of hashes? Are they more memory efficient?

lundi 1 janvier 2018

Rails 3.2.16 has_many collection build failure

Have a legacy application in Rails 3.2.16 which evaluating for an upgrade and have found an issue when running tests related to an ActiveRecord association between two models. The problem is that the when attempting to construct the associated collection it fails.

I've tested the same scenario is a simple test app using the Ruby on Rails Getting Started Guide which works (details below). The one difference between my test app and the legacy app is that the legacy app models have a number of validations on them.

The models are as follows (extra details removed for ease of reading):

class Schedule < ActiveRecord::Base
    has_many :bookings
    ...
end

class Booking
   belongs_to :schedule
   validate :ensure_sufficient_capacity
   ...
end

The bookings_controller for the new action has the following sequence:

class BookingController < ApplicationController

  def new
      #find the named schedule
      @schedule = Schedule.find_by_name("myschedule")

      #build the booking
      @booking = @schedule.bookings.build(:name => "mybooking",...)

      @booking.save #fails to save
  end

end

Some observations:

  1. The booking model has a validation on it which does a check onto a referenced schedule (the other side of the relation. Can failure on the validation cause a break in the association build ?

  2. Creating a test app as per the Rails Guides Post-Comments getting started example works with a sample of the output below shows that the has_many build operation works.

local> p = Post.new(:title => "foo")

local> #

local> p.save

local> INSERT into "posts" ("title") VALUES ($1) RETURNING "id" [["title", "foo"]]

local> c = p.comments.build(:commenter => "bar")

local> #

local> c.save

local> INSERT INTO "comments" .......