mardi 29 novembre 2016

Heroku Doesn't Detect Language

I'm creating a rails app on c9.io.

There is a main dir called rails-tutorial and a sub dir for the actual app called hello_app.

hello_app is a rails app.

when I say git push heroku master. It fails and the reason as I see in the activity logs of heroku is unable to detect language.

My question is: Since git is pushing the whole dir, is heroku not able to find the gemfile in the root to figure out that it is a ruby/rails app?

I've also tried to copy the gemfile to the root dir, that has also not worked.

What am I doing wrong?

Inherit a base model to another model

Hi guys im making a movie website(with RoR) for educational proposes and i had an idea but i cant thin a way to put this into code, im gonna insert my db design down below.

"Movie inheritted BaseEntity" <-- Example

How to use joint query in this association - Ruby on Rails

I am working in ruby 2.1.5 and rails 3.2.1. I want to list all the company in grid which is associated to company_name = John

Company table:

enter image description here

company model:

has_many :partner_relationships, :class_name => "CompanyRelationship",:foreign_key => 'parent_id',

company_relationships table:

enter image description here

I want to get all the company information from company table where company.id = partner_id. I tried the below query

Company.joins(:partner_relationships).where('company_relationships.parent_id' => company.id)

This is returning 3 set of same data that is <#id:2, company_name:John, description:I am John#>

I want to return the records as follows <#id:1, company_name:Jose, description:I am Jose#>, <#id:3, company_name:George, description:I am George#>,..<#id:5, company_name:Alwin, description:''#>

Please help me in solving this.

How can I allow multiple error rendering messages in rails api response

I am trying to render error messages if any of the condition fails. How can I pass error messages related to failed conditions

But it gives me AbstractController::DoubleRenderError error

def create
    if @current_wbp_user && params[:user_id] && params[:note_id] && params[:comment] && params[:hashtag]
      user = User.find_by(id: params[:user_id])
      if user.present?
        if user.access_code != @current_wbp_user.access_code
          render json: {errors: "User not associated with this wbp user"}, status: :unprocessable_entity
        end
        note = Note.find_by(id: params[:note_id])
        if note.present?
          if note.user_id != user.id
            render json: {errors: "Invalid note for this user"}, status: :unprocessable_entity
          end
        else
          render json: {errors: "Note not found"}, status: :unprocessable_entity
        end
      else
        render json: {errors: "User not found"}, status: :unprocessable_entity
      end
      @comment = @current_wbp_user.wbp_user_comments.build(wbp_user_comments_params)
      if @comment.save
        render json: {success: true}, status: :ok
      else
        render json: {errors: "Comment could not be created"}, status: :unprocessable_entity
      end
    else
      render json: {errors: "Insufficient Information"}, status: :unprocessable_entity
    end
  end

lundi 28 novembre 2016

Use hmset / hmget in REDIS: WRONGTYPE Operation against a key holding the wrong kind of value

I am trying to use hmset / hmget to store hashmaps associated to a key in REDIS as such:

def self.store_id_and_phone(key, id, phone)
  REDIS.hmset(key, :id, id, :phone, phone)
  REDIS.expire(key, 15.minutes)
  verification_code_url_key
end

def self.get_id_and_phone(key)
  return REDIS.hmget(key, :id, :phone)
end

However I sometimes get this error at REDIS.hmget

WRONGTYPE Operation against a key holding the wrong kind of value

It doesn't happen all the time tho, about 3% of all the requests.

Did anyone encounter similar issues before? Please shed some light. Thanks!

includes method in Ruby on Rails 3

Why does includes method behaves like select distinct

One blog has many 10 comments.
includes output remove same record. But find_by_sql doesn't remove same record. why??

# includes
1.9.3-p551 :023 > Blog.includes(:comments).where(comments: {id: [1..40]})
  SQL (0.6ms)  SELECT "blogs"."id" AS t0_r0, "blogs"."name" AS t0_r1, "blogs"."created_at" AS t0_r2, "blogs"."updated_at" AS t0_r3, "comments"."id" AS t1_r0, "comments"."blog_id" AS t1_r1, "comments"."created_at" AS t1_r2, "comments"."updated_at" AS t1_r3 FROM "blogs" LEFT OUTER JOIN "comments" ON "comments"."blog_id" = "blogs"."id" WHERE (("comments"."id" BETWEEN 1 AND 40 OR 1=0))
 => [#<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">] 

# find_by_sql
1.9.3-p551 :024 > Blog.find_by_sql("select blogs.* from blogs left outer join comments on comments.blog_id = blogs.id where (comments.id between 1 and 40)")
  Blog Load (0.3ms)  select blogs.* from blogs left outer join comments on comments.blog_id = blogs.id where (comments.id between 1 and 40)
 => [#<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">] 

Programatically sort dhtmlxgrid in ruby on rails

I want to sort dhtmlxgrid with data on the server side, I realized that there is a PHP library present here.

Is there a way I can achieve this in Ruby On Rails?

Can anyone please point me to right direction or some reference links? Thanks.

samedi 26 novembre 2016

How to set route for a rendered action? Rails

i'm new to mvc, rails and web development and i'm facing a problem:

I have an action(show) and a view for this action.

The view for show submits a form_tag to another action, that renders the action show.

The problem is, I have no idea how to set a route for the action that renders show.

Right now my routes.rb is:

resources :meals do
collection do
  get "meals/:id", to: "meals#show"
end

end

Tried to add these but didn't work:

match "meals/:id/calculate" , :to => "meals#calculate",:via => [:get]

and:

get "meals/:id/calculate", to => "meals#calculate"

Generating preview image thumbnails of uploaded files on Rails

I'm using Rails to create a website that allows users to upload document files with various file formats (pdf, doc, docx, ppt, pptx, xls, xlsx, png, jpg, jpeg) and store them on aws S3. I'm using Carrierwave to directly upload files to S3, and everything works well so far. Uploaded files are nicely stored in S3.

But now, I want to display preview images (thumbnail images) for uploaded files. I've tried several different methods by manipulating Carrierwave configuration, but it seems like generating thumbnail images only works on PDF files, not other file formats. Can anyone please give me any insight to make this work? Thanks

Rails - how to build association in new action for namespaced resource

I am trying (and failing miserably) to understand some basic things about rails. I am a student on code school, gorails and a bunch of others. I'm not figuring out how to join the dots on these basic things - and it's driving me nuts - Im 4+ years in to trying to learn but I have not managed to grasp the basic building blocks of rails.

I have models called Organisation and Stance::Assessment. The associations are:

Organisation

  has_one :assessment, class_name: Stance::Assessment, inverse_of: :organisation
    accepts_nested_attributes_for :assessment,  reject_if: :all_blank, allow_destroy: true

Stance::Assessment

  belongs_to :organisation, inverse_of: :assessment

My routes are:

resources :organisations 


namespace :stance do
    resources :assessments
   end

On my organisation show page, I'm trying to add a link allowing a user to assess the organisation's policy. The Stance::Assessment resource has the form to provide this assessment.

On my organisation show page, I have:

    <%= link_to 'Assess this policy', new_stance_assessment_path(organisation: @organisation), class:'btn btn-blue btn-line' %>

In the bracketed part of this path, I'm trying to get the stance_assessment path to recognise the organisation that is currently showing.

In the stance assessment form, I have:

<%= simple_form_for(@assessment) do |f| %>
  <%= f.error_notification %>

 <% @assessment.errors.full_messages.each do |msg| %>
    <%= li= msg %>
 <% end %>
  <div class="form-inputs" style="margin-bottom: 50px">
    <%= f.hidden_field :organisation_id, :value => @organisation.id %>

    <div class="row">
      <div class="col-md-10 col-md-offset-1" style="margin-top: 50px">
        <%= f.input :comment, as: :text, label: "Assess this policy", :input_html => {:rows => 10} %>
      </div>
    </div>
  </div>

I have tried to give a hidden field so that the organisation_id saved in the stance_assessment table is the organisation.id of the path that led to this form. That part is a guess -I've tried lots of variations on where to put this and how to express it, but I can't find anything that works.

In my stance assessment controller, new action, I'm trying to define the organisation. I have:

  def new
    @assessment = Stance::Assessment.new
    @organisation = Organisation.find(params[:id])
    # authorize @assessment
  end

However, this isn't any good, because it generates an error that says:

Couldn't find Organisation with 'id'=

I don't understand what this error means. All of my organisations have an :id attribute.

If it's something to do with the organisation_id attribute in the stance assessments table not being set by the time it's trying to do the new action (which does make sense), I'm then lost for how to set this when the form will always need to use the new action.

In my organisation controller, I have built the association with assessment as:

def new
    @organisation = Organisation.new
    @organisation.build_assessment

This all works fine if I nest the form fields for assessment inside of the organisation form. I don't want to do that because I want a different user (not the organisation owner) to complete the assessment - so I want the assessment form inputs in a different form.

Can anyone help?

vendredi 25 novembre 2016

rails has many relation through other table

I have 4 tables, All of them are connected to each other.

restaurant -> has_many -> menus
menu -> has_many -> categories
category -> has_many -> menu items

I tried to access categories from restaurant through menu table and it is not working

I want to access categories and menu items from restaurant table, is it possible

for example

Restaurant.find(1).categories
Restaurant.find(1).menu_items

Save at same time, error handeling

Let's say I have this simple association:

class Post < ActiveRecord::Base
  has_many :comments # :autosave option is not declared
end

And this code:

post = Post.new(title: 'ruby rocks')
post.comments.build(body: 'hello world')
post.save # => saves both post and comment

What happens if post is invalid, does it still create the comment?

What happens if the attached comment is invalid, does it still create the post?

I would like that when comment or post is invalid, it saves nothing. Am I doing the right thing?

Do I need validates_associated ?Thanks

unzip .bin file programaticall in ruby

I have a .bin which i am trying to unzip programatically. The directory is a temp directory in which the.bin file is saved.

I have tried to the following

change the permission of bin files by typing.
chmod -c 777 filenam.bin.
now run the bin file by typing

I shows error as illegal option c.

Can anyone help. Thanks.

jeudi 24 novembre 2016

Undefined method `embroderies' for nil:NilClass for submit create form

I set up submit form to add new data, but I got this error undefined methodembroderies' for nil:NilClass.` I was following the rails guide for that but I have no idea how can I correct my code.

Here is my controller.

class EmbroderiesController < ApplicationController
  def index
  end

  def show
    @embroderies = Embrodery.find(params[:id])
  end

  def new
    @embrodery = Embrodery.new
  end

  def create
    @region = Region.find(params[:region_id])
    @embrodery = @region.embroderies.create(comment_params)

    if @embrodery.save
      redirect_to @embrodery
    else
      render 'new'
    end
  end

  private
  def embrodery_params
    params.require(:embrodery).permit(:name, :image)
  end
end

The view

<div class = "container">
  <div class = "row">
    <div class = "col-xs-12 add-wrap-div">
      <p>Add new model</p>
      <%= form_for ([@region, @region.embroderies.build]) do |f| %>
        <p>
          <%= f.label :name %><br>
          <%= f.text_field :name %>
        </p>

        <p>
          <%= f.label :image %><br>
          <%= f.file_field :image %>
        </p>
        <br>
        <br>
        <p>
          <%= f.submit %>
        </p>
      <% end %>
    </div>
  </div>
</div>

and the routes

               Prefix Verb   URI Pattern                                        Controller#Action
                 root GET    /                                                  home#index
           home_index GET    /home/index(.:format)                              home#index
           home_about GET    /home/about(.:format)                              home#about
   region_embroderies GET    /regions/:region_id/embroderies(.:format)          embroderies#index
                      POST   /regions/:region_id/embroderies(.:format)          embroderies#create
 new_region_embrodery GET    /regions/:region_id/embroderies/new(.:format)      embroderies#new
edit_region_embrodery GET    /regions/:region_id/embroderies/:id/edit(.:format) embroderies#edit
     region_embrodery GET    /regions/:region_id/embroderies/:id(.:format)      embroderies#show
                      PATCH  /regions/:region_id/embroderies/:id(.:format)      embroderies#update
                      PUT    /regions/:region_id/embroderies/:id(.:format)      embroderies#update
                      DELETE /regions/:region_id/embroderies/:id(.:format)      embroderies#destroy
              regions GET    /regions(.:format)                                 regions#index
                      POST   /regions(.:format)                                 regions#create
           new_region GET    /regions/new(.:format)                             regions#new
          edit_region GET    /regions/:id/edit(.:format)                        regions#edit
               region GET    /regions/:id(.:format)                             regions#show
                      PATCH  /regions/:id(.:format)                             regions#update
                      PUT    /regions/:id(.:format)                             regions#update
                      DELETE /regions/:id(.:format)                             regions#destroy

schema

ActiveRecord::Schema.define(version: 20161115165517) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "embroderies", force: :cascade do |t|
    t.string   "name"
    t.string   "image"
    t.integer  "region_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "embroderies", ["region_id"], name: "index_embroderies_on_region_id", using: :btree

  create_table "regions", force: :cascade do |t|
    t.string   "name"
    t.string   "image"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_foreign_key "embroderies", "regions"
end

Ruby hash returning strange values

I am returning a response of user fields in JSON. I am creating JSON as below.

def user_response(users)
    users_array = []
    users.each do |user|
      uhash = {}
      uhash[:id] = user.id,
      uhash[:nickname] = user.nickname,
      uhash[:online_sharing] = user.online_sharing,
      uhash[:offline_export] = user.offline_export,
      uhash[:created_at] = user.created_at,
      uhash[:app_opens_count] = user.app_opens_count,
      uhash[:last_activity] = user.last_activity,
      uhash[:activity_goal] = user.activity_goal,
      uhash[:last_activity] = user.last_activity,
      uhash[:region] = user.region
      users_array << uhash
    end
    users_array
  end

But the response is pretty weird. The :id key in hash has an array of all the fields don't know why.

{
    "nickname": "adidas",
    "online_sharing": null,
    "offline_export": null,
    "created_at": "2016-08-26T09:03:54.000Z",
    "app_opens_count": 29,
    "last_activity": "2016-08-26T09:13:01.000Z",
    "activity_goal": 3,
    "region": "US",
    "id": [
      9635,
      "adidas",
      null,
      null,
      "2016-08-26T09:03:54.000Z",
      29,
      "2016-08-26T09:13:01.000Z",
      3,
      "2016-08-26T09:13:01.000Z",
      "US"
    ]
  }

ruby (extrat the ip address last login and sort them)

First I have a file derived from the last command in Linux. But I have hard time to figure out how to extract and sort every IP address and last command for each user. This actually how the file looks like:

frank    pts/5        192.220.128.18   Thu Dec 13 21:47   still logged in 
enha     pts/3        17.0.0.206       Thu Dec 12 21:09   still logged in
skr      pts/1        184.31.240.205   Thu Dec 19 18:57 - 21:18  (02:20)
skr      pts/6        182.31.40.205    Thu Oct 24 16:42 - 16:53  (00:10)
skr      pts/7        182.31.40.205    Thu Oct 24 15:35 - 15:42  (00:06)
frank    pts/6        177.31.20.205    Thu Avr 24 15:33 - 15:42  (00:08)
sama     pts/5        190.150.128.25   Thu Avr 25 15:03 - 17:03  (02:00)
ccorn    pts/3        100.10.128.27    Thu Sep 24 14:17 - 14:26  (00:08)

And this is the output I'm looking for:

UserName,Last Login,Total Logins,IP Address List
frank,Nov 13 21:47,2,192.220.128.18;177.31.20.205
skr,Dec 19 18:57,3,182.31.40.205;188.31.40.205
sama,Avr 25 15:03,1,190.150.128.2

i was able to count for example how may each user login but i could not figure the rest and sort them as expect to be this is what I done so far

frequencies = Hash.new(0)
login = []

lines =File.readlines("file.txt")
lines.each do |line|
login << line.split[0]

end
#p login

login.each do |user|
  frequencies[user] += 1
end
  p frequencies

and thanks in advance

Error validations from child model Ruby on Rails

I got a problem which I can't solve. I made two models; one model called Film is the parent model and another model called Review is the child model. I got validation conditions on the child model but it does not display on the view.

Film model

class Film < ApplicationRecord
has_many :reviews

validates_presence_of :filmtitle,  presence: true
validates_presence_of :filmdescription,  presence: true
validates_presence_of :filmdirector,  presence: true
validates_presence_of :filmrating,  presence: true
validates_presence_of :filmstarname,  presence: true 
end

Review model

class Review < ApplicationRecord
validates :rating,  presence: true
validates :commenter,  presence: true
validates :body,  presence: true
belongs_to :film
end

Review Controller

class ReviewsController < ApplicationController
def create
    @film = Film.find(params[:film_id])
    @review = @film.reviews.create(review_params)
    redirect_to film_path(@film)
end

private
def review_params
  params.require(:review).permit(:commenter, :body, :rating)
end
end

Film show.html.erb

  <% if @film.errors.any? %>
<div id="error_explanation">
  <h2>
    <%= pluralize(@film.errors.count, "error") %></h2>
  <ul>
    <% @film.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
  </div>
  <% end %>
<%= form_for([@film, Review.new]) do |f| %>
<p>
 <%= f.label :commenter %><br>
 <%= f.text_field :commenter, :placeholder => 'Your name' %>
</p>
 <p>
 <%= f.label :body %><br>
 <%= f.text_area :body, :placeholder => 'Your comment' %>
 </p>
  <p>
    <%= f.label :rating %><br>
    <%= f.select :rating, ['1 Star', '2 Stars', '3 Stars', '4 Stars', '5    Stars'] %>
 </p>
  <p>
 <%= f.submit %>
  </p>
 <% end %>

Film Controller

class FilmsController < ApplicationController
before_action :set_film, only: [:show]

# GET /films
# GET /films.json
def index
@films = Film.all.paginate(page: params[:page], per_page: 30)
@reviews = Review.new
end

# GET /films/1
# GET /films/1.json
def show
end

# GET /films/new
 def new

 end

 # GET /films/1/edit
def edit
 end

# POST /films
# POST /films.json
def create

end

# PATCH/PUT /films/1
# PATCH/PUT /films/1.json
def update

end

# DELETE /films/1
# DELETE /films/1.json
def destroy

end

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

 # Never trust parameters from the scary internet, only allow the white list   through.
def film_params
  params.require(:film).permit(:filmtitle, :filmdescription)
end
 end

mercredi 23 novembre 2016

mardi 22 novembre 2016

Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead

I have created a demo application in rails 3.2.9 and ruby versiion 2.0.0 . After scaffolding Blog model I am trying to migrate it, but having following issue.

# rake db:migrate

==  CreateBlogs: migrating ====================================================
-- create_table(:blogs)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead: CREATE TABLE `blogs` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `title` varchar(255), `description` text, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB
/usr/local/rvm/gems/ruby-2.0.0-p648@demo-app/gems/activerecord-3.2.9/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `query'
/usr/local/rvm/gems/ruby-2.0.0-p648@demo-app/gems/activerecord-3.2.9/lib/active_record/connection_adapters/a

bstract_mysql_adapter.rb:245:in `block in execute'
/usr/local/rvm/gems/ruby-2.0.0-p648@demo-app/gems/activerecord-
-3.2.9/lib/active_record/migration.rb:551:in `migrate'
/usr/local/rvm/gems/ruby-2.0.0-p648@demo-app/gems/activerecord-3.2.9/lib/active_record/railties/databases.rake:179:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.0.0-p648@demo-app/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Login View in Ruby on rails

I am new to rails and I have a problem with login view, I tried to place a menu at the top of the page with CSS attributes but when I run the rails server the menu appears in the middle of the page and not up as I want. I hope it's not a stupid question but I can not find a solution I've tried everything, I hope you can help me please

STI with Polymorphism self referential

i have 4 models Group,Post,Comment and reply models

where comment and reply inherits from Post.every Group has_many comments. every comment has_many reply

my models like that

class Post < ApplicationRecord
     belongs_to :postable, polymorphic: true
end

group model

class Group < ApplicationRecord
  has_many :comments, as: :postable, class_name: "Comment"
end

comment model

class Comment < Post
  has_many :replies, as: :postable, class_name: "Reply"
end

i want to use Polymorphism with sti as follow

  1. postable_type refer to group as result of group-comment relationship

    postable_type refer to comment and equal 'comment' as result of comment-reply relationship

my problem is in the second relationship as always postable_type equal to STI base 'post' but it should to equal to 'comment' ?????.

How to create and query replies from comments?

Bitbucket Authentication failed on pushing existing project

This is the error on my terminal:

Authentication failed for 'http://ift.tt/2fYKcuO'

This is what I did:

git remote add origin ssh://git@bitbucket.org/kboygitgit/sample_app.git git push -u origin master

then it asked for my username and password

then the error showed upp:remote: Unauthorized fatal: Authentication failed for 'http://ift.tt/2fYKcuO'

I need help since I am a learning progress in rails and btw I am using rails version 5.0.0.1

redmine schedule plugin fault

I use redmine for project management. I have installed a plugin as per the steps which when run throws the following error. Please help me out.

When i delete the plugin and run, the server starts but am unable to do so when the plugin is copied to the folder.

The log is as follows:

C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-4.2.5.2/lib/a ctive_support/dependencies.rb:274:in require': cannot load such file -- holiday s/ca (LoadError) from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:274:inblock in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:240:in load_dependency' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:274:inrequire' from C:/Sites/redmine/plugins/redmine_schedules/init.rb:3:in <top (requ ired)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:274:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:274:in block in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:240:inload_dependency' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport- 4.2.5.2/lib/active_support/dependencies.rb:274:in require' from C:/Sites/redmine/lib/redmine/plugin.rb:155:inblock in load' from C:/Sites/redmine/lib/redmine/plugin.rb:146:in each' from C:/Sites/redmine/lib/redmine/plugin.rb:146:inload' from C:/Sites/redmine/config/initializers/30-redmine.rb:21:in `'

add index migration adding column instead of migration

I am trying to add a index to a column which already exists in my table by using

I want to add a index on item_id on product_images table

bundle exec rails generate migration AddIndexToProductImages item_id:integer:index

but the code i see in the migration file is

class AddIndexToProductImages < ActiveRecord::Migration
  def change
    add_column :product_images, :item_id, :integer
  end
end

Not sure what could be causing this, can anyone help? Thanks.

connect Ruby on Rails Projetc with MSSQL Server

i need to create new ruby on rails project with Mssql Server DB the new project on Linux machine and the mssql server on another machine i alrady make connection between linux and mssql server using tsql now i have to create new rails project with that mssql server

lundi 21 novembre 2016

broken image tags - In RAILS

Problem Description This application is using custom image js library (flex-slider). It's using data-thumb attributes.

<li data-thumb="images/show.jpg">
        <div class="thumb-image">
             <%= image_tag "show.jpg", data_imagezoom: "true", class: "img responsive"%>
       </div>
  </li>

In rails, it fails to pickup images on tags. I get an error on console.

show.jpg:1 GET http://localhost:3000/products/images/show.jpg 404 (Not Found)

How can I get rails to pick up these images ?

Expected Behavior enter image description here

Actual Behavior

enter image description here

Trouble Shooting Done

I've tried replacing

<li data-thumb=<%= image_tag "show.jpg"> 

OR <li data-thumb=<%=image_path("show1.jpg") %>>

AND <li data-thumb = asset_path("logo.png", image)>

Please let me know in case you need more info

Thanks

Ruby-on-Rails. block in find': Unable to find field "q" (Capybara::ElementNotFound)

GitHub project: http://ift.tt/20rNrL3

I'm a beginner, trying to execute this Ruby script.

  1. I created a database.yml file.
  2. I ran the setup file in the bin folder which installed dependenceis via bundle install and set up a database i am assuming via the commands: rake db:create rake db:migrate
  3. so i ran the following: ./bin/rails server

Created an account, filled out the "Job" and "location" and set the amount of pages to check to "1" for indeed.com.

This is the error that i have received:

Started GET "/search?utf8=%E2%9C%93&title=Engineer&location=CA&pages=10&indeed_scraper=1&commit=Find+Jobs" for 127.0.0.1 at 2016-11-19 21:00:26 -0800 Processing by JobsController#search as HTML Parameters: {"utf8"=>"✓", "title"=>"Engineer", "location"=>"CA", "pages"=>"10", "indeed_scraper"=>"1", "commit"=>"Find Jobs"} User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Running via Spring preloader in process 2763 /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/node/finders.rb:44:in block in find': Unable to find field "q" (Capybara::ElementNotFound) from /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/node/base.rb:85:insynchronize' from /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/node/finders.rb:33:in find' from /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/node/actions.rb:59:infill_in' from /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/session.rb:699:in block (2 levels) in <class:Session>' from /var/lib/gems/2.3.0/gems/capybara-2.7.0/lib/capybara/dsl.rb:52:inblock (2 levels) in module:DSL' from scraper.rb:138:in perform_search' from scraper.rb:33:inscrape' from scraper.rb:145:in <top (required)>' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/runner.rb:60:inload' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/runner.rb:60:in <top (required)>' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:inrequire' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in block in require' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:inload_dependency' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in require' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:123:inrequire_command!' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:90:in runner' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:inrun_command!' from /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/commands.rb:17:in <top (required)>' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:inrequire' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in block in require' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:inload_dependency' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in require' from /home/shap/Desktop/job-hunter-master/bin/rails:9:in<top (required)>' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:in load' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:inblock in load' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:in load_dependency' from /var/lib/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:inload' from /usr/local/lib/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require' from /usr/local/lib/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from -e:1:in

' Redirected to http://localhost:3000/users/jobs Completed 302 Found in 8221ms (ActiveRecord: 0.2ms)`

What is going on here?

Heroku displaying pagination different from locally

I am following an online tutorial for Ruby on Rails.

Everything seems to be working but the Heroku deployment shows different page for the Pagination.

Follow the images. HEROKU: Heroku

Locally: Locally & Codes:

app/views/index.html.erb

<% provide(:title, 'All users') %>
<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
  <%= render @users %>
</ul>
<%= will_paginate %>

app/views/users/_user.html.erb

<li>
  <%= gravatar_for user, size: 50 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <%= link_to "delete", user, method: :delete,
                                  data: { confirm: "You sure?" } %>
  <% end %>

</li>

custom.scss

...   
 /* Users index */

    .users {
      list-style: none;
      margin: 0;
      li {
        overflow: auto;
        padding: 10px 0;
        border-bottom: 1px solid $gray-lighter;
      }
    }

Any clue?

dimanche 20 novembre 2016

Prawn draw 2 table side by side

I have a table made up of many cells, and in one cell i want to draw a two table side by side,

and i'm using prawn ruby gem

Ex

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

i tried like using

t1 = make_table([[cell_1],[cell2], [cell3])
t1.draw

But it comes below the first table, how do i make it side by side

Error while using 'rails server' command

I have installed Ruby on Rails using railsinstaller-3.2.0 [Ruby version:2.2.4 ,Rails version : 5.0.0.1].
Error facedWhenever I Run 'rails server' command I confront an error report like [Could not find gem 'uglifier (>= 1.3.0) x86-mingw32' in any of the gem sources listed in your Gemfile or available on this machine.].Even if Install the required gem new error is raised for another missing gem . How can I solve this issue , How can I install all the missing gems ?

Active admin nested form not working Error: too many arguments for format string

Following is my code block of state Model, SatatImage Model and Active Admin Code. In active admin when I try to create a new record or Edit a --record that time I show an error on production server. but works on my localhost in development mode, ---------Error---------------------------

too many arguments for format string

app/admin/state.rb:49:in `block (2 levels) in '

I am using Ruby 1.9, Rails 3,2, activeadmin (0.6.0)

======State Model===============
class State < ActiveRecord::Base

   attr_accessible :name, :code
   validates :code, :uniqueness => true
   has_one :state_image, :dependent => :destroy
   accepts_nested_attributes_for :state_image, :allow_destroy => true
   .......
 end

==============StatImage Model=============

class StateImage < ActiveRecord::Base
  attr_accessible :state_id, :stateimage, :image_name

  belongs_to :state
  mount_uploader :stateimage, StateUploader
end


=======Active Admin part=================

ActiveAdmin.register State do
 .....

 form(html:{multipart:true}) do |f|

   f.inputs "State Form" do
     f.input :name, required:true
     f.input :code, required:true
   end

  #line-49#  
 f.inputs "StateImage", for:[:state_image, f.object.state_image ||   StateImage.new] do |p|
     p.input :stateimage, :as => :file, :label => "Image" 

   end
   f.buttons :submit
 end

end

How to sort ActiveRecord Relation results on a custom logic?

I have a table containing a number of location objects(columns are id, latitude and longitude). I select rows from this table based on some query, then for these results, I want to find the distance of each location (using latitude and longitude of this point) from a custom point. How do I sort it on a manual logic? Here is what I tried:

# Location Model

def self.search(params, fields, user, employee_id)
    marker = SearchHelper.change_to_point(params[:marker_distance_sort])

    results = self.select(columns_selected)
            .intersect_query(boundary)

    # What should I do here for custom sorting?
    results.sort_by { |a, b| a.distance_from_marker(marker) <=> b.distance_from_marker(marker)}

end

def self.distance_from_marker(marker)
    marker.distance(FACTORY.point(self.attributes['longitude'], self.attributes['latitude']))
end

Sorry I am really new to ruby on rails and I have tried every resource available on stack overflow answers for custom sorting. Thanks for the help!

send_file in rails 5 stopped the browser from downloading

after upgrading to Rails 5, sending a file using:

send_file file_url, :type=>"application/pdf", :x_sendfile=>true, disposition: params[:disposition]

stopped downloading the file, instead, it opens the following like window (same window)

enter image description here

samedi 19 novembre 2016

Implementing Ruby on Rials search but getting "Couldn't find all Listings with 'id':"

I'm trying to implement a search function on my site following this rails cast. However it's not really working and it displays...

Couldn't find all Listings with 'id': (all, {:conditions=>["title LIKE ?", "%Example%"]}) (found 0 results, but was looking for 2)

I tried looking around for what is going on and found this question on the site, tried implementing the fixes for it since I suppose Rails Cast is using a very old version of rails. Though I am still getting the same thing.

listing_controller.rb search method

def search
    @listing = Listing.where(id: params[:id]) if params[:id].present?
    @listing = Listing.search(params[:search]) if params[:search].present?
end

listing.rb

def self.search(search)
    if search
        find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
    else
        find(:all)
    end
end

index.html.erb

  <p>search shiplist</p>
  <%= form_tag search_listings_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
  <% end %>

How to access attributes/values of instances within an array

I have a form that shows me the business days for a two-week period (10 days). I want to loop over each day and check to see if each day lands on a holiday. If it does, I want to show a label on that row that displays the name and description of the holiday.

Currently my code works to show a holiday. However, it will only show 1 holiday in any two-week period. I believe this is because I have the .first method tacked onto my map and select blocks. But if I remove the .first I receive an error on my calendar helper tool tip because it can no longer access the holiday description attribute.

How can I change this code so that it loops through each day, checks to see if it's a holiday, and then accesses the instance of the holiday class so I can get to the value of the name and description attributes?

Right now I'm just trying to make this work on the _form, not worrying about the index page at this point.

Any help would be appreciated!

Contoller:

class TimesheetsController < ApplicationController

  def index
    @all_timesheets_for_user = current_user.timesheets
    @timesheets = current_user.timesheets.yearly_timesheets(@year).by_pay_period_ending_desc 
    current_user.log("Timesheets", "User's List", nil, current_admin, browser)
    @holiday_dates = Holiday.all
  end 

  def new
    @timesheet = Timesheet.new(user_id: current_user.id, pay_period_ending: params[:pay_period], timesheet_type: 'salary')
    @holiday_dates = Holiday.all
    @timesheet.build_days(@timesheet.timesheet_days.map{|d| d.day})
  end

  def edit
    @timesheet = Timesheet.find(params[:id])   
    @holiday_dates = Holiday.all 

    @timesheet.build_days(@timesheet.timesheet_days.map{|d| d.day})
    @timesheet.timesheet_days.sort_by!{|d| d.day}
  end
end

The holiday model includes the following attributes:

#  id          :integer          not null, primary key
#  start_date  :date
#  end_date    :date
#  name        :string(255)
#  description :text
#  all_day     :boolean
#  date_type   :string(255)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null

This is the _form.html.haml that is causing the issue.

.table-responsive
  %table.table.table-condensed.table-striped.table-bordered.table-hover
    %tr
      %th Day
      %th Date
      %th Time Reporting Code
    = f.fields_for :timesheet_days do |d| 
      %tr
        %td
          = d.object.day.strftime("%A")
          = d.hidden_field :day
          .type= d.hidden_field :timesheet_type
        %td
          = d.object.day.strftime("%b %d, %Y")

        # -----HOW CAN I ACCESS THE INSTANCES OF THE HOLIDAY CLASS WITHOUT USING FIRST HERE?-----
          - if @holiday_dates.map{|h| (h[:start_date]..h[:end_date]).include?(d.object.day)}.first

            - holiday = @holiday_dates.select{|h| d.object.day >= h[:start_date] && d.object.day <= h[:end_date]}.first

            .message.label.label-xs.bold.render-tooltip.pointer{title: "#{date_tool_tip(holiday)}", id: "event-#{holiday.id}", class: "label-#{date_classes(holiday)} event-#{holiday.id}", data: {id: "#{holiday.id}"}, style: "z-index: 1000; word-wrap: break-word;"}= holiday.name
            :javascript
              $('.render-tooltip').tooltip();  

          - else
            # do other stuff

Delayed job: Set max run time of job , not the worker

I have below piece of code :

Converter.delay.convert("some params")

Now I want this job to be run for max 1 minute. If exceeded,delayed job should raise the exception.

I tried setting up

Delayed::Worker.max_run_time = 1.minute 

but it seems it sets a timeout on the worker , not on the job.

Converter class is defined in RAILS_ROOT/lib/my_converter.rb

Trying to Execute Ruby Code for the first time.

Project: http://ift.tt/20rNrL3

Background:

Took only 2 intro course on Java 7 years ago.

So I was browsing GitHub and ran across this nifty project that deals with scraping & applying for jobs on indeed.com.

The question is, how do you run it? Here is what I tried to do:

Tried to execute applier.ru I figured I was doing something wrong after getting:

/home/shap/Desktop/job-hunter-master/applier.rb:19:in initialize': uninitialized constant JobApplier::Job (NameError) from /home/shap/Desktop/job-hunter-master/applier.rb:169:innew' from /home/shap/Desktop/job-hunter-master/applier.rb:169:in `'

Something was missing, so looking around I found the bin folder and tried executing /bin/setup.ru but i ran into this error:

== Preparing database == /var/lib/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/application/configuration.rb:110:in database_configuration': Cannot loadRails.application.database_configuration`: Could not load database configuration. No such file - ["config/database.yml"] (RuntimeError)

Are we supposed to generate our own database file? how would we do that?

Any help or even a push in the right path is deeply appreciated.

SSL certificate Error While installing ruby on rails

I have installed Ruby on Rails using railsinstaller-3.2.0 [Ruby version:2.2.4 ,Rails version : 5.0.0.1].But while using the command 'rails new' I am confronting an error .I also face another problem while using 'bundle install',it returns an exception 'The system cannot find the path specified.'

Why is this not the same code

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

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

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

  def call
    @controller = context.controller

    controller.sign_in user
    controller.redirect_to remove_from_url(url)
  end

But when I change it to:

  def call
    @controller = context.controller

    controller do
      sign_in user
      redirect_to remove_from_url(url)
    end
  end

Then the tests fail, as message I get:

expected exactly once, not yet invoked ...

Why does this code not do the same?Thanks

1)  controller.sign_in user
    controller.redirect_to remove_from_url(url)

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

vendredi 18 novembre 2016

Grape api with devise token auth

I am using grape gem, devise_token_auth, grape_devise_token_auth and i'm able to sign up and sign in, it is returning access token in the header

access-token →ssssssssssssss
client →sssssssssssssss
expiry →1480743645
token-type →Bearer
uid →sssssssssss@gmail.com

But if i access a url with these details in the header of the next url, the url still shows 401 unauthorized, how do i authenticate these url for ex /api/v1/list_users

Capistrano 3 deploy failure - Rails 3.2

I've got a Rails app that I deploy using capistrano 3. The app has deployed successfully for over a year now but today after making a few changes to html files the deployment fails with the following message:

no ruby in PATH/CONFIG
 DEBUG [a202e059] 
 DEBUG [a202e059]       /home/takebackdemo/.rbenv/versions/2.1.0/bin/ruby /home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/bin/rake assets:precompile:all RAILS_ENV=developm
ent RAILS_GROUPS=assets
 DEBUG [a202e059] 
 DEBUG [a202e059]       rake aborted!
 DEBUG [a202e059]       Command failed with status (1): [/home/takebackdemo/.rbenv/versions/2.1.0/b...]
 DEBUG [a202e059]       /home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:12:in `ruby_rake_task'
/home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:21:in `invoke_or_reboot_rake_task'
/home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:29:in `block (2 levels) in <top (required)>'
 DEBUG [a202e059]       Tasks: TOP => assets:precompile
 DEBUG [a202e059]       (See full trace by running task with --trace)
(Backtrace restricted to imported tasks)

As I said, the only changes I made were to a few html files. When I run ruby -v I get:

ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin13.0]

Why would this happen?

Rails not loading model.rb file

I don't know why, but for some reason my nested association is not being respected by rails.

My student class has nested associations: addresses, tests

The addresses association works fine. The tests association, which is identical to the addresses association, does not work....??

Here's the student model:

class Student < ActiveRecord::Base
  unloadable

  validates :name, presence: true, length: {maximum: 50}

  has_many :addresses, :dependent => :destroy
  has_many :tests, :dependent => :destroy

  accepts_nested_attributes_for :addresses,
    :reject_if => :all_blank,
    :allow_destroy => true
  accepts_nested_attributes_for :tests,
    :reject_if => :all_blank,
    :allow_destroy => true
end

Here's the addresses model (which works):

class Address < ActiveRecord::Base
  belongs_to :student
  validates :address, presence: true, length: {maximum: 80}

def self.ransackable_attributes(auth_object = nil)
    ['county', 'zip', 'address']
  end
end

And here's the (basically) identical tests model (which doesn't work):

class Test < ActiveRecord::Base
  belongs_to :student
  validates :name, length: {maximum: 40}

  def self.ransackable_attributes(auth_object = nil)
    ['score', 'date']
  end
end

I feel like I didn't create my model correctly or something, and Rails doesn't know it's there? It's completely ignoring the validation as well as the ransack function.

Rails 3 : How to insert Record in Database using Rails(HTML5)

NOTE I HAVE ALREADY READ THIS : Rails 3 : How to insert Record in Database using Rails

I am using Rails 3 .

Please let me know how can i insert a Record in the Database .

I am uisng MYSQL , and below is my Table structure to be correct schema.rb in db folder

 ActiveRecord::Schema.define(version: 20161107113839) do

  `create_table "allusers", force: :cascade, options: "ENGINE=InnoDB `DEFAULT   CHARSET=latin1" do |t|`
  t.string   "username",    limit: 50, null: false
  t.string   "email",       limit: 50
  t.string   "password",    limit: 50
  t.string   "likedvideos", limit: 50
  t.datetime "created_at",             null: false
  t.datetime "updated_at",             null: false
  end

end

This is my Controller file user1_controller.rb

 class User1Controller < ApplicationController
 def user1index
 end

This is my Model file alluser.rb

class Alluser < ApplicationRecord
end

This is my view file under \app\views\user1\user1index.html.erb

 <form <% @student,:action => :new, :method => :post %> >
    username: <input type="text" name="username" /><br />
    email: <input type="text" name="email" /><br/>
    password:<input type="password" name="password" /><br/>
    likedvideos: <input type="text" name="likedvideos" /><br/>

  </form>

If i do this i get an error . Y ?

<form <% @user1,:action => :new, :method => :post %> >

this line gives me an error says ruby expected after user n after :action n after :method . What do i do ?

Plz help according to my file names n not the file names of ppl in the link on d top. THNX

call ajax function onclick event with parameters

In bootstrap modal i want to call this get_translated_content('','#{post['id']}','','','fb_posts') function. But I am not able to call this function this way. Is there any html syntax issue or else ?

<span class="pull-right"> <small class="mb-sm fa-stack"><a href="#" data-toggle="modal" data-target="#translated_fb_content" onclick = "get_translated_content('','#{post['id']}','','','fb_posts'); return false", title="Translated Content"><em class="mb-sm fa fa-circle fa-stack-2x text-primary"></em> <em class="mb-sm fa fa-info-circle fa-stack-1x fa-inverse text-white"></em> </small></a>&nbsp;&nbsp;&nbsp;&nbsp; </span>

Grape token auth "error": "404 API Version Not Found"

I am using rails application, setup grape, and trying to authenticate all the endpoints. So tried grape token auth http://ift.tt/2fBXMGu and setup as told in the github doc. These are my configurations.

initializers/gta.rb

GrapeTokenAuth.setup! do |config|
  config.mappings = { user: User }
  config.secret   = 'aaa'
end

For api this is the folder structure

app/api/tmo/api.rb -> mounted two version root file
app/api/tmo/vl/root.rb -> mounted all the other files for v1
app/api/tmo/vl/restaurants.rb -> here lies the mount authentication

include GrapeTokenAuth::MountHelpers
include GrapeTokenAuth::TokenAuthentication
mount_registration(to: '/auth', for: :user)
mount_sessions(to: '/auth', for: :user)
mount_token_validation(to: '/auth', for: :user)
mount_confirmation(to: '/auth', for: :user)

So my routes are like

Running via Spring preloader in process 9309
POST       /auth/api/v1(/.:format)
DELETE     /auth/api/v1(/.:format)
PUT        /auth/api/v1(/.:format)
POST       /auth/api/v1/sign_in(.:format)
DELETE     /auth/api/v1/sign_out(.:format)
GET        /auth/api/v1/validate_token(.:format)
GET        /auth/confirmation/api/v1(/.:format)
GET        /api/v1/statuses/public_timeline(.:format)

When i access /api/v1/statuses/public_timeline it says 401 unauthorized, so authenticate_user! method is working

But when i post to /auth/api/v1 i get the following error

{  
  "error": "404 API Version Not Found"
}

How do i check where the error is happening or how do i solve this?

jeudi 17 novembre 2016

How to call active record's association method if we have same menthod name in current model

I am new to Ruby and Rails and I did following code

class Department
end
class Employee
  field :depaertment_id, :default => nil
  belongs_to :department, :autosave => false
  def department
    dept = self.super.department # check whether associated department object exists as per self.department active record's method
    if dept.nil?
      #other operation
    end
  end
end

Here from department method I need get department object

If I do following code then department object is easily available as per rails association

class Employee
 field :depaertment_id, :default => nil
 belongs_to :department, :autosave => false
 def get_department
   dept = self.department 
   if dept.nil?
     #other operation
   end
 end
end

Please help me, How can i get department object Thanks in advance.

How can I dynamically access all config parameters starting with 'var' defined in config/applications.rb?

In my config/applications.rb, I have set parameters:

config.var1 = 1
config.var2 = 5
config.varx = 7

I can access them using

Rails.application.config.var1

I am trying to dynamically build a hash of all config parameters with names starting with 'var', so the output would be

{var1: 1, var2: 5, varx: 7}

I have looked at the Rails.application.config.methods, Rails.application.config.instance_variables, Rails.application.config.inspect etc. and they don't return the var1 etc.

How can I dynamically access all config parameters starting with 'var' defined in config/applications.rb?

Thanks for your help.

ruby on rails installed successfully but project not opening on localhost

I downloaded a website based on ruby on rails on my machine and tried to run it on my localhost. but it is not running. i have installed rails 4.0.2 and ruby 2.2.4p230. when i run the commands like cd welspun(the name of the folder where i stored the website files) and rails s i get the following message on cmd. i do not understand how to tackle this issue. i am using windows 7. please help me out. i have no knowledge of ruby on rails. please help me out.

C:\Sites>cd welspun

C:\Sites\welspun>rails s C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-4.0.2/lib/act ive_support/values/time_zone.rb:282: warning: circular argument reference - now C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9-x86-mingw32/l ib/sqlite3.rb:6:in require': cannot load such file -- sqlite3/sqlite3_native (L oadError) from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9- x86-mingw32/lib/sqlite3.rb:6:inrescue in ' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9- x86-mingw32/lib/sqlite3.rb:2:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:91:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:91:in block (2 levels) in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:86:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:86:in block in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:75:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:75:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler.rb:106:inrequire' from C:/Sites/welspun/config/application.rb:7:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:74:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:74:in block in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:71:intap' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:71:in <top (required)>' from bin/rails:4:inrequire' from bin/rails:4:in `'

C:\Sites\welspun>rails s C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-4.0.2/lib/act ive_support/values/time_zone.rb:282: warning: circular argument reference - now C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9-x86-mingw32/l ib/sqlite3.rb:6:in require': cannot load such file -- sqlite3/sqlite3_native (L oadError) from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9- x86-mingw32/lib/sqlite3.rb:6:inrescue in ' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.9- x86-mingw32/lib/sqlite3.rb:2:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:91:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:91:in block (2 levels) in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:86:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:86:in block in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:75:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler/runtime.rb:75:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6 /lib/bundler.rb:106:inrequire' from C:/Sites/welspun/config/application.rb:7:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:74:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:74:in block in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:71:intap' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.0.2 /lib/rails/commands.rb:71:in <top (required)>' from bin/rails:4:inrequire' from bin/rails:4:in `'

C:\Sites\welspun>

Rails_admin permission on edit view of specific model

I am using rails_admin gem with rails 4. Currently I am using this method

# Authorize just admin for '/admin'
  config.authorize_with do
    redirect_to main_app.root_path unless warden.user.admin == true
  end

under config/initializers/rails_admin.rb to permit only the admin user to access the dashboard. PROBLEM: if the current user is admin and he/she is trying to change her permission to regular user (unticking) admin box then they get an error saying that no method for nil:admin - this is happening because /admin is no longer available for this regular user. QUESTION: How can I disallow the current user edit his own admin property ???

mercredi 16 novembre 2016

I18n clicking navbar link defaults back to English

I'm following the railscast guide but for some reason, when I click on a link, the params locale is not being carried over.

Here's my routes.db

Rails.application.routes.draw do
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do

get 'welcome/index'

# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".

# You can have the root of your site routed with "root"
root 'welcome#index'

resources :foods
resources :shops
resources :communities
resources :events
resources :pictures
resources :videos
resources :services

end
get '*path', to: redirect("/#{I18n.default_locale}/%{path}")
get '', to: redirect("/#{I18n.default_locale}/")

I think the main difference between my app and the railscasts is I am doing it on the application.html.erb template. So I wonder if that is affecting it.

Thanks for your time!

Rails select has_many though get the right Id

I'm trying to pass the size of a product to a order with select. the product has many sizes with has_many though. but when pass show the wrong size, someone know why?

Size Model

 attr_accessible :size
  has_many :orders 
  has_many :sizeship
  has_many :products, :through => :sizeship

Product Model

 has_many :orders
  has_many :sizeships
  has_many :sizes, through: :sizeships

Order Model

  belongs_to :cart
  belongs_to :product, touch: true
  belongs_to :size

Cart Model

  belongs_to :user
  has_many :orders

Product Controller

def show
   @product = Product.cached_find(params[:id])

  @sizes_for_dropdown = @product.sizes.collect { |s| [s.size, s.id] }

end

Cart Controller

 def add
    product = Product.find(params[:id])

    if product
     if product.buyable?(current_user)
        current_user.cart = Cart.new #if current_user.cart.nil?
        size =  product.sizes.find_by_id(params[:size_id])
        quantity = params[:quantity].to_i > 0 ? params[:quantity].to_i : 1
       order = current_user.cart.orders.find_by_product_id_and_status_and_size_id(product.id, nil, product.sizes.nil? ? nil : product.sizes.find { |l| l.id } )

        if order.nil? # create new order
          order = Order.new
          order.product = product
          order.size = product.sizes.find { |k| k.id } 

          current_user.cart.orders << order
        else # increase quantity
          order.quantity += quantity
          order.save
        end

        redirect_to product_path(product)
        flash[:success] = "Success"
      else
        redirect_to product_path(product)
        flash[:error] = " Error"

      end
    else
      redirect_to :shop, flash[:error] = 'Error'
    end
  end

Ruby on Rails : relationship with "has_many"

Mr X likes only one post made by Mr Y

How can I create a relationship between Mr X and Mr Y to see the Mr Y's posts? (to see the suggested posts)

user.rb

  has_many :posts
  has_many :liked_posts, through: :liked, source: :post

post.rb

  def liked_by?(user)
    likes.where(user: user).any?
  end

likes.rb

#  id         :integer          not null, primary key
#  user_id    :integer          not null
#  like_id    :integer          not null

Should I use uniq ?

How to send custom headers in open-uri (ruby) and check them

Found this in the following doc:http://ift.tt/2e9ePyn

Additional header fields can be specified by an optional hash argument.

open("http://ift.tt/pGelD4",
  "User-Agent" => "Ruby/#{RUBY_VERSION}",
  "From" => "foo@bar.invalid",
  "Referer" => "http://ift.tt/uOONaF") {|f|
   # ...
}

Can someone tell how to check whether they are properly working.

prevent rails server from launching if file doesnt exist

I have aws.yml

development:
  asset_host: 'abcd1234efgh@cloudfront.net'

I created assets.rb

AWS_CONFIG = Rails.application.config_for(:aws)
unless (AWS_CONFIG.nil? || AWS_CONFIG['asset_host'].nil?)
  Rails.application.config.asset_host = AWS_CONFIG['asset_host']
end

I am trying to implement the logic if aws.yml not exists then it should completely blow up and prevent the rails server from launching. Any idea how could i achieve that?

first_or_initialize is not working for relative model and creating new record each time

ccs.each do |cd|
  relative_model = main_model.relative_model.where(start_date: XYZ, end_date: XYZ).first_or_initialize
  relative_model.capacity = cd['capacity'].to_f
  relative_model.save!
end

As per above code, first_or_initialize is not working for relative model and creating new record each time.

NEED INITIAL HELP OR POINT OUT WHAT IS WRONG IN ABOVE CODE?

Routing based on role - Rails

Rails 3.2

I have 2 sets of controllers, one for admin and one for regular users.

When an admin logs in, I want them to go to the index method, in controllers/admin/tickets_contoller.rb

I have the following in my routes.rb:

namespace :admin do
  root to: 'tickets#index'
  ....

and in my application_controller.rb, I have:

def after_sign_in_path_for(resource_or_scope)
  if current_user && current_user.current_company
    view_context.can? :index, :admin
      admin_root_path
  end
end

But, when I log in as admin, it seems to be going to the standard tickets_controller, not the admin/tickets_controller

Any suggestions?

Sorting by another related model attributes - Ruby on Rails

I have two models related with each other as below

class Weed < ApplicationRecord
  has_many :user_transactions,:dependent => :destroy
end

This weed model has an attribute name county

and related model:

class UserTransaction < ApplicationRecord
  belongs_to :weed
end

Now I want to fetch records from UserTransaction model on the basis of sort by county in weed model.

Please suggest me, How can I get correct result with in minimum complexity.

Thanks.

My rails tests produce gibberish output

I just overtook a new project and the rake test produces a lot of gibberish output. Why is that the case? I tried removing all gems I don't know, but still my output is clouded. I am calling the test suite via bundle exec rake test.

Sample output - it's pages of this kind of stuff.

/Users/hendricius/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activesupport-3.2.22.5/lib/active_support/file_update_checker.rb:98: warning: File.exists? is a deprecated name,
use File.exist? instead
/Users/hendricius/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activesupport-3.2.22.5/lib/active_support/file_update_checker.rb:98: warning: File.exists? is a deprecated name,
use File.exist? instead
/Users/hendricius/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activesupport-3.2.22.5/lib/active_support/file_update_checker.rb:98: warning: File.exists? is a deprecated name,
use File.exist? instead
/Users/hendricius/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activesupport-3.2.22.5/lib/active_support/file_update_checker.rb:98: warning: File.exists? is a deprecated name,
use File.exist? instead

screenshot of the tests running

The ruby version from the .ruby-version file is 2.2.2. The installed rails version is 3.2.22.5.

My test gems are:

group :test, :development do
  # gem 'rack-mini-profiler'
  # gem 'minitest'
  gem 'minitest-rails'
  gem 'test-unit'
  gem 'shoulda'
  gem 'shoulda-matchers'
  gem 'fabrication'
  gem 'byebug'
end

I then double checked my Rakefile. It has the following content:

# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.

require File.expand_path('../config/application', __FILE__)

WooWoop::Application.load_tasks

task default: [:test]

The only other thing I could imagine would be my test_helper. I pasted the contents below. It looks good.

ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/pride"
require 'shoulda'
require 'shoulda/matchers'
# $VERBOSE=nil

# ActiveRecord::Migration.check_pending!
ActiveSupport::TestCase.test_order = :random
# Protractor test or even some dirty debugging in the rails console on test environment
# might have left some garbage on the DB. Lets make sure we start with a clean state.
# parses the response and returns it.

The only way I can silence the output is if I use RUBYOPT=W0 TEST=test/unit/shop_test.rb be rake test. Is that the only way since I am using rails 3 still?

Update:

I now tried to downgrade to ruby 2.0.0

I still get a lot of strange warnings I have never seen before.

/Users/hendricius/.rbenv/versions/2.0.0-p648/lib/ruby/gems/2.0.0/gems/carrierwave-0.10.0/lib/carrierwave/uploader/configuration.rb:89: warning: instance variable @mount_on not in
itialized
/Users/hendricius/.rbenv/versions/2.0.0-p648/lib/ruby/gems/2.0.0/gems/carrierwave-0.10.0/lib/carrierwave/mount.rb:243: warning: instance variable @previous_model_for_showcase_cov
er_picture not initialized
/Users/hendricius/.rbenv/versions/2.0.0-p648/lib/ruby/gems/2.0.0/gems/carrierwave-0.10.0/lib/carrierwave/uploader/configuration.rb:89: warning: instance variable @mount_on not in
itialized
/Users/hendricius/.rbenv/versions/2.0.0-p648/lib/ruby/gems/2.0.0/gems/carrierwave-0.10.0/lib/carrierwave/mount.rb:243: warning: instance variable @previous_model_for_manager_pict
ure not initialized
(eval):11: warning: instance variable @opening_hours_monday_from not initialized
(eval):2: warning: instance variable @opening_hours_monday_to not initialized
(eval):11: warning: instance variable @opening_hours_tuesday_from not initialized
(eval):2: warning: instance variable @opening_hours_tuesday_to not initialized
(eval):11: warning: instance variable @opening_hours_wednesday_from not initialized
(eval):2: warning: instance variable @opening_hours_wednesday_to not initialized
(eval):11: warning: instance variable @opening_hours_thursday_from not initialized
(eval):2: warning: instance variable @opening_hours_thursday_to not initialized
(eval):11: warning: instance variable @opening_hours_friday_from not initialized
(eval):2: warning: instance variable @opening_hours_friday_to not initialized
(eval):11: warning: instance variable @opening_hours_saturday_from not initialized
(eval):2: warning: instance variable @opening_hours_saturday_to not initialized

Edit:

I ultimately ended up upgrading to rails 4. All the warnings are gone.

Reset rails_admin field value

How can I reset the formatted_value on a field in rails admin. So far I tried this without much luck:

  currentId = 0
  # Fields in Projects list
  config.model 'Project' do
    list do
      field :id do
        formatted_value do
          currentId += 1
        end
      end
      field :year
      field :title
      field :intro
      field :description
      field :confidential
      field :star
      field :image
    end
    currentId = 0

mardi 15 novembre 2016

problems with ruby gem ns-api

I am trying to build an app in Rails. For my app I need to use the ns-api (dutch railways) in order to get from them the trains timetables. It exists as a gem (http://ift.tt/2fWp0YV) I use the bundler and I get the message that all the gems are ok, but when I am trying to create a controller it gives me the error that it does not recognise NSclient . This happens also when I use "require 'ns_client'" in my controller or in my configuration file. I think that although the bundler seems to work , the gem is not compatible with my Rails (ver 5.0.0) or my ruby version. Any way that I could solve this ?

Thank you in advance

enter code here

Rails no implicit conversion of Symbol into Array

implicit conversion of Symbol into Array

I'm trying to create a select from a array and is showing this error! someone have any idea why?

Product model

has_many :sizeships
has_many :sizes, through: :sizeships

Size model

has_many :sizeships
has_many :products, :through => :sizeships

Product controller

def show
@sizes_for_dropdown = @product.sizes.product(:name).collect{ |co| [co.size, co.id]}
end

How to stop accepting requests when you are upgrading your rails site?

Whenever I want to deploy my new version of rails app. I want to stop stop accepting requests from client side.

Example: User is filling form. In the back I am upgrading my rails web (not the rails or ruby version). When user submits the form while upgrade is happening or has happened, I want to show something like 'Web site has upgraded, please try again'. Is it actually possible, or some way to achieve it.

Active admin nested form not working Error: too many arguments for format string

Following is my code block of state Model, SatatImage Model and Active Admin Code. In active admin when I try to create a new record or Edit a --record that time I show an error on production server. but works on my localhost in development mode, ---------Error---------------------------

too many arguments for format string

app/admin/state.rb:49:in `block (2 levels) in '

I am using Ruby 1.9, Rails 3,2, activeadmin (0.6.0)

======State Model===============
class State < ActiveRecord::Base

   attr_accessible :name, :code
   validates :code, :uniqueness => true
   has_one :state_image, :dependent => :destroy
   accepts_nested_attributes_for :state_image, :allow_destroy => true
   .......
 end

==============StatImage Model=============

class StateImage < ActiveRecord::Base
  attr_accessible :state_id, :stateimage, :image_name

  belongs_to :state
  mount_uploader :stateimage, StateUploader
end


=======Active Admin part=================

ActiveAdmin.register State do
 .....

 form(html:{multipart:true}) do |f|

   f.inputs "State Form" do
     f.input :name, required:true
     f.input :code, required:true
   end

  #let say its line number 49

   f.inputs "StateImage", for:[:state_image, f.object.state_image ||   StateImage.new] do |p|
     p.input :stateimage, :as => :file, :label => "Image" 

   end
   f.buttons :submit
 end

end

lundi 14 novembre 2016

Rails expected, got Array

I'm looking to get a id from a array and when get it shows this on the action add Order.new

Color(#70131258622840) expected, got Array(#70131401174240)

someone have any idea why?

product model

has_many :colorships
  has_many :colors, through: :colorships

color model

  has_many :colorships
  has_many :products, :through => :colorships

product controller

def new
  Product.New
  @dropdown = @product.colors.collect { |co| [co.name, co.id] } 
end


def show
  Product.find(params[:id])
 color = product.colors.select { |i| [i.id] } 

end




def add
    product = Product.find(params[:id])
    if product
        color = product.colors.select { |i| [i.id] } 

        if order.nil? # create new order
          order = Order.new
          order.product = product
          order.color =   color        
end
end
end

Unusual ActiveRecord Behavior

I'm encountering an unexpected situation with finding/creating particular records in the following table during periods of high contention. I believe there is a race condition in the database.

  create_table "business_objects", force: :cascade do |t| 
    t.string   "obj_id",     limit: 255 
    t.string   "obj_type",   limit: 255 
    t.datetime "created_at",             precision: 6, null: false
  end 

  add_index "business_objects", ["obj_type", "obj_id"], name: "index_business_objects_on_obj_type_and_obj_id", unique: true, using: :btree

Offending code:

def find_or_create_this
 attributes = self.attributes.slice('obj_id', 'obj_type')
 BusinessObject.find_or_create_by!(attributes) 
rescue ActiveRecord::RecordNotUnique
  BusinessObject.find_by!(attributes)
end

The find in the find_or_create_by! returns nil and triggers the create! which raises a ActiveRecord::RecordNotUnique error. The rescue block catches it and attempts to find the record which caused the not unique error but it also returns nil. My expectation is that if the index uniqueness constraint is violated than the record should be committed to the table. What am I missing?

Rails how select a id on a array?

I have color has many products though colorships and products has many colors though colorships

on product controller i would like by select choose a color

def new
  Product.New
  @dropdown = @product.color_ids.collect { |co| [co.name, co.id] } 
end


def show
  Product.find(params[:id])
  current_user.find_by_color_id(product.color_ids.nil? ? nil : product.color_ids.color.id)
end

PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint

I am working on ruby 2.3.1 and rails 3.2.1. I want to create new row of record in PostgreSQL db. I have created the database table with two column and primary key id and other column which accept string.

def new_name
  label_name = LabelName.new(:id =>1, :label_name =>'testing' )
  label_name.save()
end 

If I pass the value of id, records get created otherwise I am getting the following error

PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint.

When I tried to create the record manually in PostgreSQL DB also I am getting the same error.

Please help on how to solve this error.

Thanks

Rails render_to_string using wrong format

I am encountering a problem with render_to_string using Rails 3.2.18 in which the function is trying to render the wrong view format despite its :formats option being correctly set (so for example rendering the kml view when :formats is set to text).


TL-DR version :

If I call render_to_string('foos/bar', formats: 'text', layout: false) and then render_to_string('foos/bar', formats: 'json', layout: false), the later renders bar.text instead of bar.json


Long version :

I have a FoosControler that uses render_to_text when its bar action is called. bar can respond to three formats : text, json and kml. Under my views, I have the three corresponding files bar.text.erb, bar.json.erb and bar.kml.erb. I also have three different tests, in which the controller is instantiated and the output of bar is tested for the different formats (so I am calling FoosControler.new.bar(format)).

If I run each of those tests independently, I have no problems at all. So :

render_to_string('foos/bar', formats: 'text', layout: false)
# => renders bar.text.erb


render_to_string('foos/bar', formats: 'json', layout: false)
# => renders bar.json.erb


render_to_string('foos/bar', formats: 'kml', layout: false)
# => renders bar.kml.erb

The problems start if I have more than one of these in my test suite. What happens is the following :

render_to_string('foos/bar', formats: 'json', layout: false)
# => renders bar.json.erb
render_to_string('foos/bar', formats: 'text', layout: false)
# => renders bar.text.erb
render_to_string('foos/bar', formats: 'json', layout: false)
# => renders bar.text.erb instead of bar.json.erb !

From the moment I rendered bar.text.erb, any call to render_to_string with the json format renders bar.text.erb instead of bar.json.erb like it is supposed to.

The same happens between kml and txt :

render_to_string('foos/bar', formats: 'text', layout: false)
# => renders bar.text.erb
render_to_string('foos/bar', formats: 'kml', layout: false)
# => renders bar.kml.erb
render_to_string('foos/bar', formats: 'text', layout: false)
# => renders bar.kml.erb instead of bar.text.erb !

I can't seem to understand why this problem happens, as the problem isn't linked to the views - they all exist and can be rendered as shown before. Even stranger, everything works if I force the format in the render instead of using the :format parameter :

render_to_string('foos/bar.text', layout: false)
# => renders bar.text.erb
render_to_string('foos/bar.kml', layout: false)
# => renders bar.kml.erb
render_to_string('foos/bar.text', layout: false)
# => renders bar.text.erb like it is supposed to

A few other precisions :
- It doesn't matter whether I use formats: '<format>' or formats: ['<format>']
- The problem happens regardless of whether I use the different render_to_string inside the same controller using a breakpoint or whether I simply call the sequence of FoosController.new.bar(format) in the test, so the following two give the same result :

FoosController.new.bar
    render_to_string('foos/bar', formats: 'kml', layout: false)
    # => renders bar.kml.erb
    render_to_string('foos/bar', formats: 'text', layout: false)
    # => renders bar.kml.erb instead of bar.text.erb !


FoosController.new.bar('kml')
# => renders bar.kml.erb
FoosController.new.bar('text')
# => renders bar.kml.erb instead of bar.text.erb !

Any idea what can cause this unwanted behavior ? Forcing the format like I did seems to patch the issue, but I'd still want to know what exactly is going on.

dimanche 13 novembre 2016

include concern requires devise authentication

I have concern created in my controller:

module MyConcern
  extend ActiveSupport::Concern

  included do
    require 'cgi'
    require 'application/backend/todo'
    require 'application/backend/parser'
    include Application::Backend::Todo
    include Application::Backend::Parser
  end
end

And I am calling it on controller:

include MyConcern

But when I trigger method create for example, it throws me to sign in with the following error: {"error":"Please sign-in to continue."}.

The question is, how to call the particular concern without requiring devise authentication?

Redirect back with errors

I have a controller:

controller/streets_controller.rb

class StreetsController < ApplicationController
  before_action :set_street, only: [:show, :edit, :update, :destroy]

  def show
    @house = @street.houses.build
  end

  .......

And a view for that show action. There I also display a form to create new street houses:

views/streets/show.html.erb

<h1>Street</h1>
<p>@street.name</p>

<%= render '/houses/form', house: @house %>

When somebody submits the houses/form the request goes to the houses_controller.rb

class HousesController < ApplicationController

  def create
    @house = House.new(house_params)

    respond_to do |format|
      if @house.save
        format.html { redirect_back(fallback_location: streets_path) }
        format.json { render :show, status: :created, location: @house }
      else
        format.html { redirect_back(fallback_location: streets_path) }
        format.json { render json: @house.errors, status: :unprocessable_entity }
      end
    end
  end

So far it works that when somebody inserts correct house_params it redirects back and creates the house correctly

But when somebody inserts wrong house_params it redirects_back but it doesn't show the house errors in the form, it shows the form for a new house @house = @street.houses.build

How can I redirect to the StreetsController with the @house object, so that the errors are shown and also the house form is filled?

Thanks

samedi 12 novembre 2016

To convert ruby unpack equivalent in java

I am complete noob in rails and never worked on it. I have a ruby code,

token.unpack('m0').first.unpack('H*').first

which is converting

R1YKdH//cZKubZlA09ZIVZQ5/cxInvmokIACnl3MKJ0=

to

47560a747fff7192ae6d9940d3d648559439fdcc489ef9a89080029e5dcc289d

I need to implement the same functionality in Java. Can anyone please help me out with this.

rails return tuples with common attributes

I want to display all the movies by selected director. Routes and controller work fine. However, the filtered movies shown in view are all the same. For example, I have four movies of which two have the same director. What I want is to show these two different tuples in view page, but the shown two tuples are the same. This is the controller code:

def find_movies_by_same_director
  @movie = Movie.find(params[:id])
  @director = @movie.director
  if (not @director.nil?) and (not @director.empty?)
    #@movies = Movie.find_all_by_director(@director) if (not @director.nil?) and (not @director.empty?);
    @movies = Movie.find_by_sql("SELECT * FROM movies i WHERE i.director == '#{@director}'")
    render :director 
  else
    flash[:notice] = "'#{@movie.title}' has no director information"
    redirect_to root_path
  end
end    

I try both ways, find_by_sql and find_by_all, to find the tuples, but they both get the same results. This is the view code:

%tbody
- @movies.each do |movie|
  %tr 
    %th= @movie.title
    %th= @movie.rating
    %th= @movie.release_date

I'm new to rails, so any comments or suggestion will be appreciated.

Does Rails submit form need protection from SQL injections or XSS attacks?

I am developing a secure Rails app on a secure internal server, though I still want to protect it from any kind of SQL injections or XSS attacks. I know that if I have a search box I can use something like this in my MODEL to protect the app from SQL injections:

def self.search(search)
    Project.where("project_title LIKE ?"                 
                   "%#{search.strip}%"
end

What about having a submit form with direct actions to a database, say a form on projects/new do I need to protect that input from SQL injections as well, and if so, how can I achieve this?

joins from belongs_to where query not working

I have been trying joins from the has_many table and i'm able to get it like Order has_many order_items

Order.joins(:order_items).where(order_items: {name: 'something'})

But if i try from belongs_to table like

OrderItem.joins(:order).where(order: {value: 'something'})

I tried searching with keyword belongs_to, joins i wasnt able to get it

vendredi 11 novembre 2016

Rails pass has many thought to a action

On has many thought select option

  1. product has many colors thought => colorship
  2. color has many products thought => colorship
def show
  Product.find(params[:id])
  @colors_for_dropdown = @product.colors.collect { |co| [co.name, co.id] }
end

<%= select_tag :color_id, options_for_select(@colors_for_dropdown.unshift(['Select Color', nil])) %>

I tried to add the color of product that the user choose on the cart. but i'm getting error, someone have ant tip or idea what is wrong?

def add
  product = Product.find(params[:id])



 if product
    current_user.cart = Cart.new 

    color = product.colorship.first.color.name 

     current_user.cart.orders.find_by_product_id_and_color_id(product.id, nil, 
color.nil? ? nil : color.id)
          end
        end

ruby multiple or condition in a range

Is there an elegant way of achieve the following in ruby way?

x = nil #(sometimes it can be value)

y = 0 || 1 || 2 || 3 || 4

z = x || y #(if x is not nil then x else 0 || 1 || 2 || 3 || 4)

Thanks

Autoincrement postgre DB id field in RAILS

I am trying to make an autoincrement id field into a postgre DB in rails. I am trying to get the maximum id and then just add +1 and pass it down to create method. I am not quite sure what I am doing wrong, but if I have 4 projects and add the 5th one, that is getting id 5, but if I delete that one and try to add another one, that's getting id 6, not 5 again. Here is my code:

 # GET /admin/projects/new
  def new
    @project = Project.new
    @project.id = Project.maximum(:id).next.to_i

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # GET /admin/projects/1/edit
  def edit
    @project = Project.find(params[:id])
  end

  # POST /admin/projects
  def create
    @project = Project.create(params[:project])

    respond_to do |format|
      if @project.save
        format.html { redirect_to projects_path, notice: 'Project was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end

I tried to add @project.save to new, but as much as I understand, the .save should only be done in the create method. Any ideas will be kindly appreciated :D

jeudi 10 novembre 2016

Michael Hartl's Rails Tutorial ( USER TOUR )

http://ift.tt/1sNjiYF

I am confused on this part 2.2 User Resource on the book

I need help on this I cannot navigate to users or tour users Using this command: URL Action Purpose /users index page to list all users /users/1 show page to show user with id 1 /users/new new page to make a new user /users/1/edit edit page to edit user with id 1

The error says:

The page you were looking for doesn't exist. You may have mistyped the address or the page may have moved. If you are the application owner check the logs for more information. I am not sure what is wrong with this did I miss something before this step to navigate users

An error occurred while installing capybara-webkit (1.6.0), and Bundler cannot continue

Get this error when running bundle install.


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

current directory: /Users/david/Code/app/vendor/bundle/ruby/2.3.0/gems/capybara-webkit-1.6.0 /usr/local/opt/ruby/bin/ruby -r ./siteconf20161110-13713-18epbxz.rb extconf.rb sh: qmake: command not found * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/Cellar/ruby/2.3.1_2/bin/$(RUBY_BASE_NAME) --with-gl-dir --without-gl-dir --with-gl-include --without-gl-include=${gl-dir}/include --with-gl-lib --without-gl-lib=${gl-dir}/lib --with-zlib-dir --without-zlib-dir --with-zlib-include --without-zlib-include=${zlib-dir}/include --with-zlib-lib --without-zlib-lib=${zlib-dir}/lib Command 'qmake LIBS\ +\=\ -L/usr/local/opt/libyaml/lib\ -L/usr/local/opt/openssl/lib\ -L/usr/local/opt/readline/lib' not available

extconf failed, exit code 1

Gem files will remain installed in /Users/david/Code/app/vendor/bundle/ruby/2.3.0/gems/capybara-webkit-1.6.0 for inspection. Results logged to /Users/david/Code/app/vendor/bundle/ruby/2.3.0/extensions/x86_64-darwin-16/2.3.0/capybara-webkit-1.6.0/gem_make.out

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


If I run the command: gem install capybara-webkit -v '1.6.0' I get the following error


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

current directory: /usr/local/lib/ruby/gems/2.3.0/gems/capybara-webkit-1.6.0

/usr/local/opt/ruby/bin/ruby -r ./siteconf20161110-14012-x2x888.rb extconf.rb sh: qmake: command not found * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/Cellar/ruby/2.3.1_2/bin/$(RUBY_BASE_NAME) --with-gl-dir --without-gl-dir --with-gl-include --without-gl-include=${gl-dir}/include --with-gl-lib --without-gl-lib=${gl-dir}/lib --with-zlib-dir --without-zlib-dir --with-zlib-include --without-zlib-include=${zlib-dir}/include --with-zlib-lib --without-zlib-lib=${zlib-dir}/lib Command 'qmake LIBS\ +\=\ -L/usr/local/opt/libyaml/lib\ -L/usr/local/opt/openssl/lib\ -L/usr/local/opt/readline/lib' not available

extconf failed, exit code 1

Gem files will remain installed in /usr/local/lib/ruby/gems/2.3.0/gems/capybara-webkit-1.6.0 for inspection. Results logged to /usr/local/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0/capybara-webkit-1.6.0/gem_make.out


Any ideas? Thanks very much

rails paypal adaptive 302 redirect

i'm implementing the paypal adaptive sdk for rails https://github.com/paypal/adaptivepayments-sdk-ruby

but, after create the action buy on order controller i'm getting the 302 redirect, someone have any ideia or any tip to give.

at first i thought that is a session problem, but, after change and use permanent cookie still the same, later i thought that was the nginx with pagespeed or the passenger, or maybe is the rails verion 3.2.22?

controller:

def buy
order = Order.find(params[:id])
    store_amount = (order.total_price * configatron.store_fee).round(2)
    seller_amount = (order.total_price - store_amount) + order.shipping_cost

   @api = PayPal::SDK::AdaptivePayments.new
      @pay = @api.build_pay({
        :actionType => "PAY",
        :cancelUrl => carts_url,
        :currencyCode => "US",
        :feesPayer => "SENDER",
        :ipnNotificationUrl => ipn_notification_order_url(order),

        :receiverList => {
          :receiver => [{
            :email =>  order.product.shop.paypal,
            :amount => seller_amount,
            :primary => true},
            {:email => configatron.paypal.merchant,
             :amount => store_amount,     
             :primary => false}]},
             :returnUrl => carts_url })
 begin
             @response = @api.pay(@pay)

             # Access response
             if @response.success? && @response.payment_exec_status != "ERROR"
               @response.payKey
              redirect_to  @api.payment_url(@response)  # Url to complete payment
             else
               @response.error[0].message
               redirect_to fail_order_path(order)

             end
  end
 end

the result

URL
http://41.67.229.88/orders/1/buy
Status
Complete
Response Code
302 Moved Temporarily
Protocol
HTTP/1.1
SSL
-
Method
GET
Kept Alive
Yes
Content-Type
text/html; charset=utf-8
Client Address
/127.0.0.1
Remote Address
41.67.229.88/41.67.229.88
Connection

Timing

Request Start Time
11/9/16 18:40:11
Request End Time
11/9/16 18:40:11
Response Start Time
11/9/16 18:40:12
Response End Time
11/9/16 18:40:12
Duration
939 ms
DNS
-
Connect
-
SSL Handshake
-
Request
2 ms
Response
6 ms
Latency
930 ms
Speed
2.28 KB/s
Response Speed
357.26 KB/s
Size

Request
1.38 KB (1,417 bytes)
Header
1.38 KB (1,417 bytes)
Query String
-
Cookies
1,000 bytes
Body
-
Uncompressed Body
-
Compression
-
Response
778 bytes
Header
663 bytes
Cookies
-
Body
115 bytes
Uncompressed Body
-
Compression
-
Total
2.14 KB (2,195 bytes)