jeudi 30 novembre 2017

Rails - Sagepay - Forcing sandbox mode for transactions

Question as above. I've a form submitting a transaction and I'm trying to use it in sandbox mode to test. Whenever I submit the test details on the site I receive:

The IP address of the server sending the transaction does not match the valid IP address ranges listed in the Simulator.
The IP address Simulator sees for your server is ****.
You can add this IP in the Accounts section of Simulator if you wish.

I'm assuming when running in sandbox mode this won't be the case, however can't get it to process in sandbox mode..

I've tried using their sandbox details in my secrets.yml file: http://ift.tt/2zRcyEP

But when I do I receive

Simulator cannot find your vendor name in its database. The simulator saw the Vendor Name 'sandbox' - See more at: http://localhost:5000/portal/expeditions/redland-green-2018/17606/payment-schedule/add-payment#sthash.iuYLoZkL.dpuf

Finally in my config files:

unless Rails.env.production?
  ActiveMerchant::Billing::Base.mode = :test
end

ActiveMerchant::Billing::SagePayGateway.simulate = Rails.env.development?

When I'm in the form and throw in a binding.pry, ActiveMerchant::Billing::Base.mode returns :test and ActiveMerchant::Billing::SagePayGateway.simulate is true.

Any advice as to how I can get this form to submit in sandbox / testing mode rather than live is greatly appreciated.

how to check a record if it exists in another database

ok so I am using devise and I created devise user, In a new migrate I added two cloumns to the users table as follows:

   add_column :users, :userNum, :integer
   add_column :users, :isAdmin, :boolean, :default => false

and I created a new model called checkUser which created a migration which has a table as shown here:

class CreateCheckUsers < ActiveRecord::Migration
  def change
    create_table :check_users do |t|
      t.integer :userNum
      t.boolean :isAdmin, :default => false

      t.timestamps null: false
    end
  end
end 

Then I inserted a record into the checkUser using the following command from the console:

CheckUser.create(userNum:525252)

Now I want to check when the user enters the userNumber into the form. The checking should be as follows: If userNumber entered by user is already in checkUser table then set the field isAdmin in the users table to true, otherwise set it to false.

What should I do next ?

Thanks for your time

mercredi 29 novembre 2017

While trying to use Dropbox for creating a shared link for my file I always get the error

Bad Input: Error in call to API function "sharing/create_shared_link": request body: could not decode input as JSON I have created an App Folder and I can successfully write files to my Dropbox. All attempts on calling the methods in Dropbox.authorizedClient!.sharing generate this error. Does anyone have any idea to why?

 def upload_dropbox_image image
    app_key = ENV['AB_DROPBOX_APP_KEY_DEVELOPMENT']
    secret_key = ENV['AB_DROPBOX_APP_SECRET_DEVELOPMENT']
    p "==app key=======#{app_key}====secret key====#{secret_key}========="  
    client = 
    DropboxClient.new(ENV['AB_DROPBOX_ACCESS_TOKEN_DEVELOPMENT'])
    p "========client====#{client.inspect}=========="
    file = open(params[:contract_upload])
    file_name = params[:contract_upload].original_filename 
    p file_name
    response = client.upload("/#{Time.now.to_i}#{file_name}", file)
    result = HTTParty.post("http://ift.tt/1IGWLl2", 
:body => { :path => file.path.display  }.to_json,
:headers => { 'Authorization'=>"Bearer YB604dS5bCAAAAAAAAAACRFCvXAWXUm1lJ0bTKBO7GtnC5B_2HtXywlw2dmAXyDN",'Content-Type' => 'application/json'  } )
end

Time-based conditionals for ROR

I'm running a ROR Database-driven website operating out of C9 IDE; It's a website where users submit text through an html form to collaborate on a story, one sentence at a time.

What I'm Trying to do: I need to figure out the syntax necessary to have the database purge itself every thirty days. Broadly, I need to create an if-then statement that can run independently of either user input or my input in the background, meaning that I need a script that can be in the background whenever the server is active. Input is appreciated!

selecting username using current_user in devise

I read that the helper current_user can be called in the view. So I have something like this

<h1> Customer id <%= User.select(:username).find(current_user).id %> </h1>

The equivalent of what I am trying to do in SQL is the following

SELECT username FROM users WHERE id = current_user

I am not sure what I am doing wrong. I'm getting this error message:

undefined local variable or method `current_user' for ApplicationController:Class

Ruby Bundler Version Dependency Confusion in Lockfile

I will try and keep this focused.

When trying to move from a working bundler 1.14.6 combined with a Gemfile + Gemfile.lock to 1.15.2 or higher I ran into some failures in our old project's install. We believe that the failure is caused from a Gemfile.lock that is specified in a way that stricter parsing in 1.15.x and higher doesn't like. (found a vague reference to this in an issue posted somewhere on github, lost the reference. Manual resolution was recommended)

On the road to trying to fix it I am faced with trying to understand WHY it is failing and WHAT this has to do with it.

The error I am currently working on is shown below:

Downloading twitter-bootstrap-rails-2.1.0 revealed dependencies not in the API
or the lockfile (therubyracer (~> 0.10.1), less-rails (~> 2.2.2)).

Focussing on the less-rails problem, when I do a

gem list

I get the indication that less-rails is already at 2.2.4.

less-rails (2.2.4)

Why isn't the specified less-rails (~> 2.2.2) not happy with the 2.2.4 that is installed?

Please help me understand so I can take a run at fixing the other issues popping up.

Here is the gemfile and gemfile.lock that exhibits the problem.

Really struggling to understand this one, any help is appreciated. Thanks!

Ruby class method data filter

I have data inside of a ruby class method that i want to filter. The class method Clothes.data contains the following array

Clothes.data class method

[
  {
    "Type"=>"Sweater",
    "Size"=>"Large",
    "Material"=>"Wool"
  },
  {
    "Type"=>"Hoodie",
    "Size"=>"Medium",
    "Material"=>"Cotton"
  },
  {
    "Type"=>"Jeans",
    "Size"=>"Small",
    "Material"=>"Denim"
  }         
]

I want to filter the string "Wool" from the class method Clothes.data . And then return the string reversed. Here's what I have tried.

def nice_material
  Clothes.data.map @Material.reverse
end

This currently returns the array => ["Wool", "Wool", "Wool"] . The instance method @Material represents the first Material.

Instead, I want the method to only return the reverse of the string "Wool" ("looW")

Gibbon After member deleted, I can not add him again

I don't know if this is gem/api related question or implementation, but after deleting a member from a list, I can't add him again. I'm obtaining that

is already a list member. Use PUT to insert or update list members.

I am using the following methods to add members from a list:

class SubscribeToNewsletterService
 def initialize(user)
  @user = user
  @gibbon = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])
  @list_id = ENV['MAILCHIMP_LIST_ID']
end

def call
@gibbon.lists(@list_id).members.create(
  body: {
    email_address: @user.email,
    status: "subscribed",
    merge_fields: {
      FNAME: @user.first_name,
      LNAME: @user.last_name,
     }
   }
 )
 end
end

mardi 28 novembre 2017

Add attribute to Rails 5 model, which not exists in the database

I have tables - users and articles. It is one to many relation or user can have many articles. What I want is to select all users from users table with LIMIT 40, but include count all articles for each user - add property for each user count_articles. I am trying in this way:

def self.get_users(limit, offset)
  users = []
  order('created_at').limit(limit).offset(offset).each do |user|
    user.attributes[:count_articles] = user.articles.count
    users << user
    byebug
  end
  users
end

, but I am getting users without this attribute. If I use byebug and type in the console - user.count_articles, I can see the result of count_articles for current user, but if I type only user, I see all the attributes without count_articles.

how to print user_id using the devise gem

I currently trying to do something like this in the applicaiton.html.erb

<h1> <% print "Customer id #{current_user}"%> </h1> 

but I get nothing. the 'Customer id' is not being printed either. What am I doing wrong ?

Thanks for your time

ActiveRecord::RecordNotFound in XController#destroy Rails 3.2. Development

I am pretty new to web development but suddenly this error appears every time I want to delete something.

ActiveRecord::RecordNotFound in XController#destroy 
Couldn't find X with id=577

It doesn't matter if it is X, Y or Z. In the database the content is deleted. I have to hit the back button in the browser to see that the X, Y or Z is deleted.

I do not redirect_to a deleted object. Even if I redirect_to an index page the error appears.

Does this have to do something with the cache? Should I clear it? Could I use expire for it?

Thank you in advance =)

ActiveRecord::StatementInvalid: TinyTds::Error: Invalid column prefix '': No table name specified

How to access data in rails console. I have establish_connection on another database. When i try to access data console. like this i got error.

Checkinout.all
  SQL (645.2ms)  USE [ZKA]
  Checkinout Load (45.0ms)  EXEC sp_executesql N'SELECT .* FROM '
TinyTds::Error: Invalid column prefix '': No table name specified: EXEC sp_executesql N'SELECT .* FROM '
ActiveRecord::StatementInvalid: TinyTds::Error: Invalid column prefix '': No table name specified: EXEC sp_executesql N'SELECT .* FROM '

I have use gem:

gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter'

In my database.yml

development_sec:
  mode: dblib
  adapter: sqlserver
  host: ***.***.**.**
  database: ABC
  username: sa
  password: pass
  port: 1433

Migration

class CreateCheckinouts < ActiveRecord::Migration
  ActiveRecord::Base.establish_connection("development_sec")
  def change
    create_table :checkinouts do |t|

      t.timestamps null: false
    end
  end
  ActiveRecord::Base.establish_connection(Rails.env)
end

model/checkinout.rb

class Checkinout < ActiveRecord::Base
    establish_connection "#{Rails.env}_sec"
end

lundi 27 novembre 2017

can't see tables in specific database using rails console

In my case. I have use two different databases in my single application. One is mysql and another one is sqlsever.

ActiveRecord::Base.connection.tables

Using this command i have see all table in my mysql database tables. But i don't know the command to see specific database table using rails console.

How can I use rails has_many with where condition using in factory?

I am using in user.rb has_many :family, -> { where ["user_type = 'family'"] } and has_one :friend, -> { where ["user_type = 'friend'"] } I want to use has_many conditions row in my user factory in traits. How can I made it ? My factory is that

FactoryGirl.define do

    factory :user do

  trait :with_family_photo do
  after(:create) do |photo|
    photo.portrait_type 'portrait_type'
    photo.family_photos << FactoryGirl.create(:with_family_photo, photo_id: photo.id)
   end
end

trait :with_friends_photo do
  after(:create) do |photo|
    photo.portrait_type 'portrait_photo'
  end
end
end
end

I hope help to me! Thanks in advance

dimanche 26 novembre 2017

migrate is not running

I made a model called user and in the timestamp_create_users.rb ( where timestamp = long number ) I have the following:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|

      t.integer :userNum, :limit => 7
      t.string :username, :limit => 32
      t.string :fname, :limit => 40
      t.string :surname, :limit => 40
      t.string :email, :limit => 50
      t.string :kNum, :limit => 8
      t.string :password, :limit => 80
      t.boolean :isTeacher, :default => false
      t.timestamps null: false

    end
  end
end

The problem is that it gives me a long error message and here the head of it:

rake db:migrate

== 20171126181930 CreateUsers: migrating ======================================
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "userNum" integer(7), "username" varchar(32), "fname" varchar(40), "surname" varchar(40), "email" varchar(50), "kNum" varchar(8), "password" varchar(80), "isTeacher" boolean DEFAULT 'f', "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 

and the user.rb ( inside the model ) is empty. What am I doing wrong ?

Thanks for your time

What part of the class name is a module?

In a rails project I have the class:

class Police::Office 
end

Now I create an Interactor in the same namespace:

class Police::Office::ConstructInteractor 
end 

1. Is this allowed or can it provoke name clashes?

2. What is Police::Office::ConstructInteractor?

Is it a class in a module like:

module Police::Office
  class ConstructInteractor 
  end
end 

Or a class in a class?

class Police::Office
  class ConstructInteractor 
  end
end

Thank you

samedi 25 novembre 2017

Remove URL GET param for locale Rails 5

I have different languages in my app and I am using this pattern: /:locale/some-action. Most of my routes are in this scope :locale - routes.rb:

scope "(:locale)", locale: /fr|en/ do
  root to: 'home#index'
  get 'contacts', to: 'contacts#index'
end
get 'about', to: 'about#index'

, but some of them are not. For routes which are in this scope :locale, if I use their names like contacts_path, Rails generates the route depends on the locale. If it is :fr, generated route will be /fr/contacts.

For routes which aren't in this scope. For the example about. If I use its name about_path and locale is :fr, the generated URL will be /about?locale=fr, but I don't want this.

What is the way to remove this GET parameter, but still using routes which are in scope :locale with their names and generated URLs depends on :locale ?

Save Model errors to flash Rails 5

I want to add hash with model errors to flash and after that redirect. This is the controller:

def update
    current_user.update_attributes(user_params)
    if current_user.errors.any?
        flash.keep[:errors] = current_user.errors.messages
    end
    byebug
    redirect_to edit_path
end

This is the view:

<div>
    <%=f.text_field :fname, placeholder: 'First Name', limit:50 %>
        <span><%=flash[:errors][:first_name]%></span>
</div>

<div>
    <%=f.text_field :lname, placeholder: 'Lirst Name', limit:50 %>
    <span><%=flash[:errors][:last_name]%></span>
</div>

With byebug, if I fill in inputs with invalid data and type in the console flash[:errors], I see this output hash:

{:first_name=>["First name must be minimum 1 character", "is invalid"], :last_name=>["is too short (minimum is 1 character)", "is invalid"]}

If I add in the view instead <span><%=flash[:errors][:first_name]%></span>, but :

<%=flash[:errors]%>

I see the same hash as a string in HTML:

<span>
   {"first_name"=>["First name must be minimum 1 character", "is invalid"],
   "last_name"=>["is too short (minimum is 1 character)", "is invalid"]}
</span>

How can I add and use hash with flash messages in Rails 5 ?

Minimagic remove alpha doesn't work (Windows 10). Rails 5 with MiniMagic

I have an app Rails 5 with Carrierwave for uploading images and MiniMagic. I want when the image is uploaded to convert to .jpg and if it is transparent, to set white background. I know that Minimagic is a wrapper for ImageMagic and I have installed it in Windows.

Everything works fine in Linux, but in Windows removing alpha channel does not work. This is my uploader (CarrierWave):

version :thumb do
  process :process_image
end

def process_image
  manipulate! do |image|
    image.combine_options do |img|
      img.alpha 'remove'
      img.trim
      img.resize      "50x50>"
      img.resize      "50x50<"
    end
    image.format 'jpg'
  end
end

In Linux works fine (set white background and removes alpha channel), but in Windows it just doesn't upload the image, if I am using img.alpha 'remove'. Without it, it upload image, resize it, convert it to jpg, but with black background, because alpha channel is not removed.

How to remove alpha channel of the image in Windows with Minimagic and ImageMagic ?

Bootstrap starter template navbar toggler keep rolling up

I using bootstrap starter template and when i'm using it on mobile, the navbar toggler keep rolling up when you click on the button. Causing the user not able to navigate to other pages as the toggler rolls up immediately once the user click the button. Here's the link to my template:http://ift.tt/2A7V9qw Here's my code:

Pooptimer

    <div class="collapse navbar-collapse" id="  navbarsExampleDefault">

    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="/timers/new">Timer<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/users/profile">Profile</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/about">About</a>
      </li>
      <li class="nav-item">
        <%if logged_in? %>

        <%= link_to 'Sign out', sign_out_path, method: :delete ,:class => "nav-link" %>
        <% else %>
        <%= logged_in? %>
        <a class="nav-link " href="/login">Sign In</a>
         <% end %>
      </li>

    </div>
</nav>

vendredi 24 novembre 2017

How to deploy Rails application on client premises(external server)

How can I securely deploy a Rails application to client's on-premises server and prevent viewing and modification of source code.

Client has physical and root access to the server.

can it be done with linux container like docker or any other?
is it possible to create a encrypted linux container that nobody(even root) has access to and requires a username/password to login and access files.

or is it possible to create a compiled executable that doesn’t allow access to the source code?

any other solutions?

My "Delete Comment" function from my Ruby on Rails Blog Website doesn't work and I don't know why

My "Delete Comment" function from my Ruby on Rails Blog Website doesn't work and I don't know why.

Here is my error:

Routing Error No route matches [POST] "/posts/17/comments/9" Rails.root: C:/Sites/blog Routes Routes match in priority from top to bottom

"comments_controller.rb" file:

class CommentsController < ApplicationController
def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:name, :body))

    redirect_to post_path(@post)
end

def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy

    redirect_to post_path(@post)
end
end

"_comment.html.erb":

<div class="comment clearfix">
<div class="comment_content">
    <p class="comment_name"><strong><%= comment.name %></strong></p>
    <p class="comment_body"><%= comment.body %></p>
    <p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago</p>
</div>

<p>
    <%= link_to 'Delete', [comment.post, comment],
                method: :detele,
                class: "button",
                data: {confirm: 'Are you sure?'} 
    %>
</p>
</div>

"_form.html.erb":

<%= form_for([@post, @post.comments.build]) do |f| %>

<%= f.label :name %><br>
<%= f.text_field :name %><br>

<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>

<br>
<%= f.submit %>
<% end %>

"show.html.erb":

<div id="post_content">
<h1 class="title">
    <%= @post.title %>
</h1>

<p class="date">
    Submitted <%= time_ago_in_words(@post.created_at) %> Ago
    | <%= link_to 'Edit', edit_post_path(@post) %>
    | <%= link_to 'Delete', post_path(@post),
          method: :delete,
          data: { confirm: 'Are you sure?' } %>
</p>

<p class="body">
    <%= @post.body %>
</p>

<div id="comment">
    <h2><%= @post.comments.count %> Comments </h2>
    <%= render @post.comments %>

    <h3>Add a comment: </h3>
    <%= render "comments/form" %>
</div>
</div>

"posts.rb":

class Post < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true
validates :body, presence: true
end

"routes.rb":

Rails.application.routes.draw do

resources :posts do 
    resources :comments
end

root "posts#index"
end

I really don't know how to fix this. Please help me. Thank you! <3

jeudi 23 novembre 2017

Getting Format in Mailer View in Rails

In my Rails app, I use a method in my Mailer views for creating a link that takes a format param based on whether it's in html or text format.

mailer_link_to( url, link_text, format )

Depending on the format, it either creates an anchor <a> tag for html or just shows the url for text.

So for each Mailer method, I have two views:

myemail.html.erb
myemail.text.erb

In myemail.html.erb, I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "html" ).

In myemail.text.erb I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "text" ).

What I'm wondering is if I can determine what the format is so I'm not having to duplicate myself so much and specify "html" or "text" each time.

If I was in a normal view/controller, I would do something like request.format but the request object isn't available in the Mailer views.

Thanks!

mercredi 22 novembre 2017

File to import not found or unreadable: bootstrap3/bootstrap/mixins in rails 3.2

I get this error "Sass::SyntaxError in Users#index" when the submit button in clicked and next page is loaded.

I have used Ruby - 2.2.4 and Rails - 3.2.2 in my application. Below are my errors and related code. If someone had the same issue before and fixed it please let me know the solution. Thank you!!!

In my gemfile, this is the version of sass-rails:

gem 'sass-rails', '~> 3.2.6'

This is the error I get in the page:

    Sass::SyntaxError in Users#index

Showing /Users/Joe/Documents/foodsapp/app/views/layouts/v3.html.haml where line #39 raised:

File to import not found or unreadable: bootstrap3/bootstrap/mixins.
Load paths:
  Sass::Rails::Importer(/Users/Joe/Documents/foodsapp/app/assets/stylesheets/v3.scss)
  /Users/Joe/Documents/foodsapp/vendor/assets/stylesheets
  /Users/Joe/Documents/foodsapp/lib/assets/stylesheets
  (in /Users/Joe/Documents/foodsapp/app/assets/stylesheets/v3.scss)

In /Users/Joe/Documents/foodsapp/app/views/layouts/v3.html.haml, line #39 the code is :

39  = stylesheet_link_tag('v3')

In v3.scss I have imported the file, the code is:

@import 'v3/mixins';

Rails. Dropdown1 enables Drobdown2 selection using Ruby on Rails

I have two DropDowns (say DropDown1 and DropDown2) in my _form.html.erb. Here is the _form.html.erb's code (Where I need assistance);

  <div class="input-group">
    <%= f.label :flight_id %><br>
    <%= f.collection_select :flight_id, Flight.all, :id, :airline %>
  </div>
  <div class="input-group">
    <%= f.label :seat_no %><br>
    <%= f.text_field :seat_no %>
  </div>
  <div class="input-group">
    <%= f.label :hotel_id %><br>
    <%= f.collection_select :hotel_id, Hotel.all, :id, :hotel_name %>
  </div>
  <div class="input-group">
    <%= f.label :room_no %><br>
    <%= f.text_field :room_no %>
 </div>

Here I want to convert the seat_no and room_no as dependent Drop down lists, dependent on Flight and Hotel respectively. When I select Flight Seats against that Flight should become available in the Seat drop down list, and same logic for the Room drop down list.

Thanks in advance.

mardi 21 novembre 2017

Ruby on Rails - buttons position on a blog website - SASS

I want that my "New post" and "Log out" buttons from my blog website to be in the right side of the header. But they are in left, under the "All posts"...print screen of my project

"application.html.erb" file:

 <!DOCTYPE html>
 <html>
 <head>
<title>Blog</title>
 <%= csrf_meta_tags %>

 <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
 <%= stylesheet_link_tag 'application' , 'http://ift.tt/1mkHRpY' %>

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>

<body>
<div id="sidebar">
    <div id="logo">
        <%= link_to root_path do%> 
            <%= image_tag "logo.svg" %> 
        <% end %> 
    </div>

    <ul> 
        <li class="category">Website</li>
        <li><%= link_to "Blog", root_path %></li>
        <li>About</li>
    </ul>

    <ul>
        <li class="category">Social</li>
        <li><a href="">Facebook</a></li>
        <li><a href="">GitHub</a></li>
        <li><a href="">Gmail</a></li>
    </ul>

    <p class="sign_in">Admin Login</p>
</div>
</div>

<div id="main_content"> 
  <div id="header">
        <p>All posts</p>

        <div class="bottons">
            <button class="button"><%= link_to "New Post", new_post_path %>
    </button>
            <button class="button">Log Out</button>
        </div>
    </div>

    <% flash.each do |name, msg| %> 
        <%= content_tag(:div, msg, class: "alert") %>
    <% end %>

    <%= yield %>
</div>
</body>
</html>

"application.css.scss" file:

@import 'normalize';

html, body {
font-family: 'Raleway', sans-serif;
 }

 h1, h2, h3, h4, h5, h6 {
font-weight: 500;
 }

 a {
text-decoration: none;
color: inherit;
 }

#sidebar {
width: 250px;
position: fixed;
left: 0;
top: 0;
height: 100%;
background: #f5f7f9;
padding: 7em 0 0 0;
border-right: 1px solid #d6dce0;
#logo {
    width: 40px;
    position: absolute;
    right: 3em;
    top: 3em;
}
ul {
    list-style: none;
    text-align: right;
    padding-right: 3em;
    .category {
        font-weight: 700;
        font-size: 0.7em;
        text-transform: uppercase;
        color: #33acb7;
    }
    li {
        padding: .5em 0;
        a {
            color: #9eafba;
            text-decoration: none;
            transition: all .4s ease;
            &:hover {
                color: #33acb7;
            }
        }
    }
    .active {
        a {
            color: #33acb7;
        }
    }
}
.sign_in {
    position: absolute;
    right: 3em;
    top: 80%;
    font-size: .8em;
    color: #9eafba;
}
}

   .button {
   outline: none;
   background: transparent;
   border: 1px solid #d6dce0;
   padding: .5em 1.5em;
   border-radius: 1.5em;
   &:hover {
        border: 1px solid #33acb7;
        color: #33acb7;
        a {
        color: #33acb7 !important;
        }
      }
    }

 .clearfix:after {
  content: ".";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
  }

 #main_content {
margin-left: 250px;
#header {
    padding: 1em 3em;
    border-bottom: 1px solid #d6dce0;
    background: #f5f7f9;
    color: #9eafba;
    p {
        display: inline;
    }
    a {
        color: #9eafba;
        text-decoration: none;
    }
    .buttons {
        float: right;
        margin-top: -6px;
        .button {
            font-size: .8em;
            margin-left: .5em;
        }
    }
}
.post_wrapper {
    padding: 3em;
    border-bottom: 1px solid #d6dce0;
    .title {
        margin: 0;
        a {
            font-weight: 500;
            text-decoration: none;
            color: #2a2f35;
            font-size: 1.5em;
            &:hover {
                color: #33acb7;
            }
        }
    }
    .date_and_author {
        color: #9eafba;
        margin: .5em 0 0 0;
    }
}
#post_content {
    padding: 1em 3em;
    .title {
        font-weight: 500;
        text-decoration: none;
        color: #2a2f35;
        font-size: 2.5em;
        margin-bottom: 0;
    }
    .body {
        font-size: 1.1em;
        line-height: 1.75;
    }
    .date_and_author {
        color: #9eafba;
        margin: .5em 0 2em 0;
    }
    #comments {
        h2 {
            margin: 3em 0 1em 0;
            border-bottom: 1px solid #d6dce0;
            padding-bottom: 0.5em;
        }
        h3 {
            margin-top: 2em;
        }
        .comment {
            border-bottom: 1px solid #d6dce0;
            padding: 1.5em 2em;
            .clear_both {
                clear: both;
            }
            &:after {
                clear: both;
            }
            .comment_content {
                float: left;
                .comment_name {
                    margin: 1em 0 0 0;
                    font-size: 0.7em;
                    text-transform: uppercase;
                }
                .comment_body {
                    font-size: 1.2em;
                    margin: 0.2em 0 0 0;
                }
                .comment_time {
                    margin-top: 1.2em;
                    font-size: .8em;
                }
            }
            .button {
                float: right;
            }
        }
        input[type="text"], textarea {
            width: 50%;
        }
    }
}
#page_wrapper {
    padding: 3em;
    #profile_image {
        width: 300px;
        float: left;
        margin-right: 2em;
        img {
            width: 100%;
            border-radius: 0.35em;
        }
    }
    #content {
        h1 {
            font-weight: 500;
        }
        p {
            font-size: 1.1em;
            line-height: 1.75;
        }
        a {
            color: #33acb7;
            font-weight: 700;
            text-decoration: none;
        }
    }
}
.links {
    margin: 2em 0;
}
input[type="text"], input[type="email"], input[type="password"], textarea {
    width: 90%;
    border: 1px solid #d6dce0;
    border-radius: .35em;
    margin-top: 10px;
    padding: .5em 1em;
    line-height: 1.75;
}
input[type="text"] {
    height: 35px;
}
textarea {
    min-height: 180px;
}
input[type="submit"] {
    outline: none;
    background: transparent;
    border: 1px solid #d6dce0;
    padding: .5em 1.5em;
    font-size: 1.1em;
    border-radius: 1.5em;
    margin-left: .5em;
    &:hover {
        border: 1px solid #33acb7;
        color: #33acb7;
    }
}
}

Please help me to move these buttons on right. Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!Thank you!

Why the instance variables can be in form_fo in HTML?

This is my code in

users_controller.rb

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

def show
  @user = User.find_by id: params[:id]
  return if @user
  flash[:danger] = t("controllers.users_controller.failed")
  redirect_to signup_path
end

def new
 @user = User.new
end

def create
  @user = User.new user_params
  if @user.save
    log_in @user
    redirect_to @user
    flash[:success] = I18n.t("controllers.users_controller.success")
  else
    render :new
  end
end

And this ís my html: _form.html.erb

<%= form_for @user, url: yield(:url) do |f| %>
  <%= render "shared/error_messages" %>

  <%= f.label :name %>
  <%= f.text_field :name, class: "form-control" %>

  <%= f.label :email %>
  <%= f.email_field :email, class: "form-control" %>

  <%= f.label :password %>
  <%= f.password_field :password, class: "form-control" %>

  <%= f.label :password_confirmation, t(".confirm") %>
  <%= f.password_field :password_confirmation, class: "form-control" %>

  <%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>

And somebody help me know that why was the instance variable (@user) be in the form_for in html?

Finger Print Digest not appending with image path in Rails 3.2.22.5

I have a css class declared in a CSS partial named '_city-images.css.scc' :

.city-art {
  background: url(image-path('cities-images.png')) no-repeat;
}

The problem is after compilation of assets via assets:precompile. The path generated by the 'image-path' helper is not generated with finger print.

The path generated is : https://abc.mysite.com/assets/cities-images.png But it should be something like : http://ift.tt/2z9og9l

Before you ask, the issue is only in .css.scss files. All the paths in other files are generating with fingerprints. Finger Printing is enabled as well in production.rb : config.assets.digest = true

I have searched a lot, but couldn't find a solution which worked.

Can any one help?

lundi 20 novembre 2017

rails 3 apache Passenger app home page says : We're sorry, but something went wrong

Webrick works fine.

I set up apache and passenger using RVM but when I try to access home page with passenger I get a blank page with this error:
We're sorry, but something went wrong. .
Here's some of my set up:

$ rvmsudo passenger-status
Warning: can not check `/etc/sudoers` for `secure_path`, falling back to call via `/usr/bin/env`, this breaks rules from `/etc/sudoers`. Run:

export rvmsudo_secure_path=1

to avoid the warning, put it in shell initialization file to make it persistent.

In case there is no `secure_path` in `/etc/sudoers`. Run:

export rvmsudo_secure_path=0

to avoid the warning, put it in shell initialization file to make it persistent.
Version : 5.1.11
Date    : 2017-11-20 21:23:15 -0500
Instance: 4f5dvobz (Apache/2.4.18 (Ubuntu) Phusion_Passenger/5.1.11)

----------- General information -----------   
Max pool size : 6
App groups    : 1
Processes     : 1
Requests in top-level queue : 0

----------- Application groups -----------   
/home/deploy/apps/tweetsifter (production):
App root: /home/deploy/apps/tweetsifter
Requests in queue: 0
* PID: 19196   Sessions: 0       Processed: 2       Uptime: 4h 32m 32s
CPU: 0%      Memory  : 606M    Last used: 2m 12s a

passenger version

$ rvmsudo passenger-config --root
Warning: can not check `/etc/sudoers` for `secure_path`, falling back to call via `/usr/bin/env`, this breaks rules from `/etc/sudoers`. Run:

export rvmsudo_secure_path=1

to avoid the warning, put it in shell initialization file to make it persistent.

In case there is no `secure_path` in `/etc/sudoers`. Run:

export rvmsudo_secure_path=0

to avoid the warning, put it in shell initialization file to make it persistent.
/home/deploy/.rvm/gems/ruby-2.0.0-p648/gems/passenger-5.1.11

In the apache error log:

WARNING: potential privilege escalation vulnerability. Passenger is running as root, and part(s) of the passenger root path (/home/deploy/.rvm/gems/ruby-2.0.0-p648/gems/passenger-5.1.11) can be changed by non-root user(s):
The path "/home/deploy/.rvm/gems/ruby-2.0.0-p648/gems/passenger-5.1.11" can be modified by user "deploy" (or applications running as that user). Change the owner of the path to root, or avoid running Passenger as root.

In the error log fileI can see some stdout/printed queries like they show on webrick.
How can I make the home page show/work ?

Why my delete post function doesn't work?

I was trying to make a simple blog application using Rails. I added function like "creating a new post", "edit a post" I wanted also to add a delete function... but it doesn't work. Please help me!

Here is my "posts_controller.rb" file

class PostsController < ApplicationController
def index
    @posts = Post.all.order('created_at DESC')
end

def new
    @post = Post.new 
end

def create
    @post = Post.new(post_params)
    @post.save

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

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

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

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

    if @post.update(params[:post].permit(:title, :body))
        redirect_to @post
    else 
        render 'edit'
    end
end

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

    redirect_to post_path
end

private 
    def post_params 
        params.require(:post).permit(:title, :body)
    end
end

"show_html.erb" file:

<div id="post_content">
<h1 class="title">
    <%= @post.title %>
</h1>

<p class="date">
    Submitted <%= time_ago_in_words(@post.created_at) %> Ago
    | <%= link_to 'Edit', edit_post_path(@post) %>
    | <%= link_to 'Delete', post_path(@post),
          method: :delete,
          data: { confirm: 'Are you sure?' } %>
</p>

<p class="body">
    <%= @post.body %>
</p>
</div>

And it gave me this error: ActiveRecord::RecordNotFound in PostsController#show Couldn't find Post with 'id'=7 Extracted source (around line #22):

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

def edit 

THANK YOU!

samedi 18 novembre 2017

angular4 and rails as backend athentication

I have an application in rails 3.4 implementing authentication using gem authlogic. I want to implement the front-end with angular4 how to handle the authentication in angular4 and rails3 that use authlogic.

rails adding /admin to routes when admin logs in

In my project I have a users model and an advertisements model. The users model contains the admins too. I want to set routes such that when an admin logs in, all URLs contain "/admin" in them. I am new to rails and having some trouble with the same. For example, when a regular user signs in, the url is /advertisements/:id/show but when an admin signs in, the URL becomes /admin/advertisements/:id/show. Tried a lot of methods but couldn't find any solution to do it. My User migration file is as follows:

class CreateUsers < ActiveRecord::Migration[5.1]

def change create_table :users do |t| t.string :first_name, limit: 15, null: false t.string :last_name, limit: 15 t.string :username, limit: 20 t.string :email, null: false t.string :password_digest t.boolean :approved, default: false t.boolean :admin, default: false t.timestamps end end end

My Advertisements migration file is:

class CreateAdvertisements < ActiveRecord::Migration[5.1]
  def change
    create_table :advertisements do |t|
      t.string :name, null: false
      t.text :description, null: false
      t.integer :price, null: false
      t.string :location, null: false
      t.integer :user_id
      t.boolean :approved, default: false
      t.timestamps
    end
    add_index("advertisements", "user_id")
  end
end

the routes file (routes.rb) has the code

resources: users
resources: advertisements

Is there any way to do it?

jeudi 16 novembre 2017

Problems setting development environment

I have a rails 3 app working in a development environment using tmuxinator. like this:

for running the server:

RAILS_ENV=development bundle exec rails server

and for the resque

RAILS_ENV=development bundle exec rake resque:pool --trace

when I run a resque task going by the web it work OK, but when I try to run this in console (inf-ruby-console-rails with emacs or rails console)

undefined method `find' for Period:Class

it seems that activerecord is not loaded but in the console I can get the Period.find method

2.1.6 :002 > period = Period.find(225)
   (1.4ms)  SELECT table_name FROM information_schema.views WHERE table_schema = SCHEMA()
  Period Load (0.8ms)  SELECT `periods`.* FROM `periods` WHERE `periods`.`id` = 225 LIMIT 1
 => #<Period id:225 ....>
 => true

2.1.6 :008 > Activity.new({ scope: period.class, type: :update, model: period,user: nil}).log #= this launch the backgorund task
 => true

also when I launch the rake task I get this: (class Period has a class method called notify_expired, on console work but fails executing the resque task for the same reason) and sometimes the resque task doesn't find the method

ActiveRecord::SerializationTypeMismatch: attribute was supposed to be a Hash, but was a String

To get a hash I have this:

serialize :colors, Hash

But I have an error where it the result of this attribute looks like this:

To show this I took out the "Hash" from "serialize :colors, Hash" to see the error in the console.

"--- !map:ActiveSupport::HashWithIndifferentAccess \none: \"#87466d\"\ntwo: \"#307065\"\nthree: \"#c04992\"\nfour: \"#ffffff\"\nfive: \"#636467\"\n"

Not sure what's happened but seems like the Hash has become a string and I don't' know why. I didn't used to have this problem but I now have two versions of this project where the first is in rails 2 and the other is in rails 3 and I switch between the two. I feel like the error has occurred since going to rails 3 and coming back into rails 2. Anyone know how I can fix this error and why it has occurred?

I looked at a similar post and it hasn't helped me: "Attribute was supposed to be a Hash, but was a String"

mercredi 15 novembre 2017

Rails 3 association between two same name models

I have two rails models. The Class name of both models is A, but one model is inside a module Manage.

a) Class Manage :: A

b) Class A

I want to create a one-to-one relation between these two tables. When I add

belongs_to: A 

in Class Manage :: A, rails associates it with the same class.

How do I add association between these two models? I have searched a lot but haven't found anything yet.

404 error message for a particular word in url

I am displaying different websites depending on the venue name. Etc. venue called "badbooking" then the url will be badbooking.school.com, but if the venue name contains a word "space", instead of displaying the site and the url, it gives 404 error message. Only this word, any other word works. It seems to be a reserved word, but can not find any related to it in the code

Any idea why is this happening?

mardi 14 novembre 2017

Rspec testing fail strong params

Trying to get this one to pass for a while, not that familiar with Rspec, tried couple answers, and no luck yet, I have these two parameters being required on my controller as follow:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_back fallback_location: new_user_path
    else
      render :new
    end
  end
private
  def user_params
    params.require(:user).permit(:username, :password)
  end
end

and this is the rspec test that is giving me an issue:

  describe "GET #create" do
    it "returns http success" do
      get :create
      expect(response).to have_http_status(:success)
    end
  end

here is the error that I am getting:

1) UsersController GET #create returns http success
     Failure/Error: params.require(:user).permit(:username, :password)

     ActionController::ParameterMissing:
       param is missing or the value is empty: user

I am looking at the rspec documentation right now, but any help would be appreciated it.

How to get unique/distinct values in included in render json

I'd like the instituciones values to be unique/distinct when rendering profesionales.
The model is as shown:

class Profesional < ApplicationRecord
has_many :instituciones, through: :horarios

and profesionales_controller.rb goes:

render json: @profesionales.to_json(include: {
instituciones: { only: [:id] }
})

But I get some instituciones repeated. Is there a way to apply uniq or distinct?

Ruby on rails - unable to create comments. NoMethodError

I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller

class CommentsController < ApplicationController
def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
end


private
    def comment_params
        params.require(:comment).permit(:body)
    end

end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
belongs_to :forum
end

Below is the form for section from the show.html.erb for the forum page

<h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>

And this is the error from rails:

undefined method `comment' for #

with the following extract:

end

        @comment = @forum.comment.create(comment_params) #highlighted

        redirect_to forum_path
    end

how to solve a typo error in rails 4 in the form?

I have a form to create vehicals and define the route corresponding to it, But it consistently gives a typo error, I think I am doing it wrong, please correct following is the code:

<%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>
<div>
<%= vehical.label 'house power'%>
  <%= vehical.text_field 'horse_power'%>
</div>
    <div>
      <%= vehical.label 'brand' %>
      <%= vehical.text_field 'brand' %>
    </div>
    <div>
      <%= vehical.label 'model' %>
      <%= vehical.text_field 'model' %>
    </div>

    <%= vehical.submit 'create' %>
<% end %>

routes for it:

 match '/vehicals/create', :to => 'vehicals#create', :as => 'vehicals_create', :via => :post

Error:

ActionView::Template::Error (no implicit conversion of Symbol into Integer):
    1: 
    2: <%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>
    3: <div>
    4: <%= vehical.label 'house power'%>
    5:   <%= vehical.text_field 'horse_power'%>

thanks in advance

lundi 13 novembre 2017

Uncaught TypeError: $(...).datepicker is not a function in ruby on rails 3

Hi I am trying to show date picker icon near the date input field. When i am loading the screen, the date picker not showing. And it shows " Uncaught TypeError: $(...).datepicker is not a function " error in my console.Please help me to solve this issue..Thanks in advance..!

this is my function :

setTimeout(function(){
    jQuery(function() {

      var pickerOpts;

      var dateToday = new Date();

      jQuery(function($) {

        pickerOpts = {

          showOn: "button",
          buttonImage: "/assets/cal_icon.png",
          buttonImageOnly:true,
          changeMonth: true,
          changeYear: true,
          dateFormat: "dd-mm-yy",
         // minDate: dateToday,
          id:"cal"

        };
        $("#pay_date").datepicker(pickerOpts);

      });

    });
  },200);

});

Stripe payment with rails

I'm looking for a way to send money from my stripe account to someone's debit card. Does anyone know of an API that allows me to do this? I am use stripe payment getway.

I'm working in Rails.

How to routes to a specific controller with a variable value ahead of it in rails 5?

Normally its like: resources :users To keep a value ahead we can do like

scope :url do
   resources :users
end

but, problem is that I have the just variable in front of the routes not a fixed value. Example in rails 2. and want to convert the routing accoding to rails5

map.with_options :controller => 'users' do |user|
  user.forgot_user ':url/users/forgot',   :action => 'forgot',  :url => /([a-zA-Z0-9\-]*)/
  user.user ':url/users/retrieve',   :action => 'retrieve',  :url => /([a-zA-Z0-9\-]*)/
  user.login       ':url/users/login',    :action => 'login',                                          :url => /([a-zA-Z0-9\-]*)/
  user.logout      ':url/users/logout',   :action => 'logout',                                         :url => /([a-zA-Z0-9\-]*)/
  user.new_user    ':url/users/new',      :action => 'new',     :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
  user.users       ':url/users/:id',      :action => 'show',   :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
end

dimanche 12 novembre 2017

Implement directory system in rails

I want to implement directory system in my rails app. User will have some abilities to manipulate directory.

  • Create new folders and delete them.
  • User will be able to upload only validated format based files in selected folder.
  • Folders can also contains sub-folders.
  • In these sub-folders files will be uploaded.

just to get an idea of structure here is the picture.

Subtract two columns of in ruby

I Have a table Users

id Name offered used 1 John 10 8 2 michel 2 2

Sql Query

select offered-used from Users where id=1

result = 2

I required the same query in ruby

rails decimal values shows unexpected result with .9999999999 [on hold]

I am receiving a param a value with rate['row_total'] = 65.60 from request. Then in controller i get

puts "rate = #{rate['row_total']}" = 65.5999999999999

I tried BigDecimal(rate['row_total']).to_s('F') did not work

samedi 11 novembre 2017

undefined method `find_by_friendly_id' with FriendlyId gem and Rails 5.1

I want to prevent selecting user with his id and that's why I am using this method which should work in this way, but instead I am getting this error:

undefined method `find_by_friendly_id' ...

This is the user model:

include FriendlyId
friendly_id :name, :use => [:slugged, :finders]

and the controller:

def show
    @user= User.find_by_friendly_id(params[:slug])
end

I am using latest version of the gem - 5.1.0.

Set API key in rails website

I am learning payment gateway integration in rails. I chose insta mojo and was working but the documentation they provide is very inconvenient and hard to understand..

http://ift.tt/2AAdASd

I have no idea where to Set my API keys.

require 'Instamojo-rb'

api = Instamojo::API.new("c51766be718d7d5e5a5aeff00b83e202"
    , "0e268600acb0b7ea8b8414007f5f9fee"
    , "http://ift.tt/2hpZLkz")

I tried instamojo.rb in initializers and tries to run console but it gives error that no such method exists.

Integrate instamojo api in rails app

I am learning payment gateway integration in rails. I chose insta mojo and was working but the documentation they provide is very inconvenient and hard to understand..

http://ift.tt/2AAdASd

I have no idea where to Set my API keys

require 'Instamojo-rb'
api = Instamojo::API.new do |app|
  app.api_key = "api_key-you-received-from-api@instamojo.com"
  app.auth_token = "auth_token-you-received-from-api@instamojo.com"
end` 

I tried instamojo.rb in initializers and tries to run console but it gives error that no such method exists.

vendredi 10 novembre 2017

How to create Mysql test database in dockerized Rails application?

I managed to dockerize my existing Rails application running on a Mysql database. But I wonder if it is possible to setup docker-compose to create the test database in the same container?

jeudi 9 novembre 2017

Gem Load Error is: uninitialized constant Haml::Util::Sass

I shift from ruby from 1.9.3 to 2.2.5. Then this error occur while

loading rails_admin gem.

full error trace is below

/home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:84:in rescue in block (2 levels) in require': There was an error while trying to load the gem 'rails_admin'. (Bundler::GemRequireError) Gem Load Error is: uninitialized constant Haml::Util::Sass Backtrace for gem load error is: /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/haml-3.1.8/lib/haml/util.rb:348:intry_sass' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/haml-3.1.8/lib/sass/rails3_shim.rb:1:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/sass-3.5.3/lib/sass/root.rb:1:in' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/sass-3.5.3/lib/sass/util.rb:11:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/sass-3.5.3/lib/sass/version.rb:2:in' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/haml-3.1.8/lib/haml/util.rb:347:in try_sass' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/haml-3.1.8/lib/sass.rb:6:in' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bootstrap-sass-2.3.2.2/lib/bootstrap-sass/sass_functions.rb:1:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bootstrap-sass-2.3.2.2/lib/bootstrap-sass.rb:10:inload!' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bootstrap-sass-2.3.2.2/lib/bootstrap-sass.rb:51:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/rails_admin-0.0.5/lib/rails_admin/engine.rb:4:in' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/rails_admin-0.0.5/lib/rails_admin.rb:1:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:inrequire' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:81:in block (2 levels) in require' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:ineach' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in block in require' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:ineach' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in require' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler.rb:114:inrequire' /home/kashif/rails/alisa/metnet/config/application.rb:7:in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:53:inrequire' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:53:in block in <top (required)>' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:50:intap' /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:50:in <top (required)>' script/rails:6:inrequire' script/rails:6:in <main>' Bundler Error Backtrace: from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:80:inblock (2 levels) in require' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:in each' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:76:inblock in require' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:in each' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler/runtime.rb:65:inrequire' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/bundler-1.16.0/lib/bundler.rb:114:in require' from /home/kashif/rails/alisa/metnet/config/application.rb:7:in' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:53:in require' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:53:inblock in ' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:50:in tap' from /home/kashif/.rvm/gems/ruby-2.2.5@metnet2/gems/railties-3.2.11/lib/rails/commands.rb:50:in' from script/rails:6:in require' from script/rails:6:in'

Any help?

Connection reset by peer - SSL_connect -> Only when logged in (devise, cancan)

I am a total newbie regarding devise and cancan and I am very lost and need at least a tip where to start. I have undertaken a ruby on rails app. I changed the data model btw. Earlier there was Project>Participant and now there is Project>Participant>Person

The error below only appears when I am logged in. If I am logged in as an admin the error appears a little less often. If I am logged in as a normal user the error appears very often.

The strange part is, when I hit F5 a couple of times after the error appeared it all works. But while hitting F5 the Extracted source changes once. The errors are below. I have absolutely no idea how to interpret this errors and why they appear. Please help me.

Error 1

Connection reset by peer - SSL_connect

Extracted source (around line #57): views/participants/_participant.html.erb

54:       <td><%=  orga.first.description %></td>
55:      <% end %>
56:   <td><%= link_to image_tag("magnifier.png", { :title => t(:show) }),     participant_person_path(participant_id: participant.id, id:     participant.person_id) %></td>
57:   <td><% if can? :destroy, participant%><%= link_to image_tag("bin.png", { :title => t(:destroy) }), [participant.project, participant], method: :delete, data: { confirm: t(:are_you_sure) } %><%end%></td>
58:     </tr>
59:   <% end %>
60: <% end %>

Application Trace | Framework Trace | Full Trace

app/models/user.rb:26:in `groups?'
app/models/ability.rb:367:in `block (2 levels) in initialize'
app/models/ability.rb:366:in `block in initialize'
app/views/participants/_participant.html.erb:57:in    `_app_views_participants__participant_html_erb___191894396_77603860'
app/views/projects/_show_private.html.erb:1153:in     `_app_views_projects__show_private_html_erb___593120840_78692430'
app/views/projects/show.html.erb:31:in     `_app_views_projects_show_html_erb___45130175_76780260'
app/controllers/projects_controller.rb:99:in `show'

Error 2

Connection reset by peer - SSL_connect

Extracted source (around line #10):

7:       <% authorization = true %>
8:     <% end %>
9:   <% end %>
10:   <% if @project.created_by == current_user.cn || current_user.admin? %>
11:     <% authorization = true %>
12:   <% end %>

Thank you in advance =)

Rails ActionCable with http authentification

I have RoR 5.0.0.1 project with ActionCable functionality. We have staging environmen with http authentification. I need ActionCable to work with our staging. What I need to do to get work ActionCable and http auth in our project? My current connection.rb file:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.email
    end

    protected
    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end

  end
end

Thanks.

Ruby on rails big decimal value format not correct

Big Decimal not showing value in numbers

a = BigDecimal.new("100.55")
a = * a * a
puts "big decimal #{a}"

output

big decimal [#<BigDecimal:ad5a6e8,'0.101103025E5',18(45)>]

How i can display it in proper format just like 12345.236

mercredi 8 novembre 2017

RoR 3 embarassing error cannot figure out

I have spend the better half of a few days and night getting a Rails intro page (index), new, edit pages up to edit users, for a post/blogging site I am working on as a project. I hope to have a working site (I am finishing a degree as well - done with last class! - this is not for school!) Anyway - this page, all.html.erb should display all users and the code is below:

all.html.erb (not copy/pasting - sorry for mistakes):

<h1>All Users:</h1>
  <%= @users = Users.all %>
  <%= @users.each do |user| %>
     <li>
     <%= user.login %>
     </li>
     <% end %>
     <li>
     <%= link_to "profile", user_path(user.id) %>
     </li>

Again sorry for any formatting mistakes - I do not usually overly format when trying to learn a new language/framework but will get to that. Sorry. I guessing this is obvious, sorry about that, I have not had a change to familiarize myself with Ruby more than what I need here. I just want this to work so I know I understand the framework first, later I will go through rails/ruby files to understand more. Thank you.

Creartor must exist error Ruby on Rails

I have two models, issues and user

User:

class User < ApplicationRecord
    has_many :created_issues, :class_name => 'Issue', :foreign_key => 'creator_id'
    has_many :assigned_issues, :class_name => 'Issue', :foreign_key => 'assigned_id'
end

Issue:

class Issue < ApplicationRecord
    belongs_to     :creator,
                   :class_name => "User",
                   :foreign_key  => "creator_id"

    belongs_to     :assigned,
                   :class_name => "User",
                   :foreign_key  => "assigned_id" 
end

Migration file:

class CreateIssues < ActiveRecord::Migration[5.1]
  def change
    create_table :issues do |t|
      t.string :title
      t.text :description
      t.integer :assigned_id
      t.string :tipo
      t.string :prioridad
      t.string :estado
      t.references :creator
      t.references :assigned

     add_foreign_key :issues, :users, column: :creator_id, primary_key: :id
     add_foreign_key :issues, :users, column: :assigned_id, primary_key: :id
      t.timestamps
    end
  end
end

Part of the schema:

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

create_table "issues", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.integer "assigned_id"
    t.string "tipo"
    t.string "prioridad"
    t.string "estado"
    t.integer "creator_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false`enter code here`
    t.index ["assigned_id"], name: "index_issues_on_assigned_id"
    t.index ["creator_id"], name: "index_issues_on_creator_id"
  end

end

in the form I'm getting that he field Creator must exists, but i see it fine in the insert:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"2yY/0x6961iIb9PxcyQAKHUSRqEj+zwQ91uPwHibU9tWjEXqiKMqp3vwzI70FVI2agtYhPgljFPDZjVZV4cmyg==", "issue"=>{"title"=>"asdsad", "description"=>"asdsa", "creator_id"=>"2", "tipo"=>"adas", "prioridad"=>"dsdaasd", "assigned_id"=>"3"}, "commit"=>"Create Issue"}
Unpermitted parameter: :creator_id
(0.1ms) begin transaction
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
(0.1ms) rollback transaction

any help ?

mardi 7 novembre 2017

Gruff Bar Chart Stop Showing up After Rails 3.2.8+ Upgrade

I am using rails 3.2.8 with the gruff gem 0.3.7 and it works great. Once I upgrade to a higher version of rails 3 my gruff charts stop showing up and I get the following errors in my logs: TypeError (no implicit conversion of nil into String): app/controllers/report_controller.rb:64:in delete' app/controllers/report_controller.rb:64:inensure in generate_chart' app/controllers/report_controller.rb:64:in `generate_chart' ....

Any advice would be great.

Ruby-on-Rails 4 edit_user_path update not updating

Just started rails so any help appreciated I have set up everything for mode User, Users login files are below:

in controllers:

def change_password
@user = User.find(params[:id])
if @user.password_hash == Bcrypt::Engine.hash_secret(:password, salt)
@user.password = params([:password])

def update
@user = User.find(params[:id])
@user.update_attribute( :login, params[:login])
@user.udpate_attribute( :password, params[:password])
change_password
if(@user.save)
    flash:[:success] = "user updated"
redirect_to 'welcome#index'
end
end

views: index just has a link to show, then to edit

edit:

<h1>Profile:</h1>
<%= form_for(@user) do |f| %>
<li>
<%= f.label :id %>
<%= f.text_area :id %>
</li>
<li>
<%= f.label :password %>
<%= f.text_area :password %>
</li>
<li>
<%= link_to "Correct? -> Save", edit_user_path(update) %>

Sorry for my lack of understanding here - where do i implement the update/change_password method. Whenever I try to call it, the error thrown is undefined method for @user - i thought I would be able to call @user.update or just update?

Below is my rails routes:

users_index  GET     /users/index(.:format)    users#index
root         GET     /                         users#index
users        GET     /users(.:format)          users#index
             POST    /users(.:format)          users#create
new_user     GET     /users/new(.:format)      users#new
edit_user    GET     /users/new(.:format)      users#edit
     user    GET     /users/:id(.:format)      users#show
             PATCH   /users/:id(.:format)      users#update
             PUT     /users/:id(.:format)      users#update
             DELETE  /users/:id(.:format)     users#destroy
users_new    get      /users/new(.:format)     users#new
             GET      /users/:id(.:format)     users#edit
             GET      /users/:id/edit(.:format)   users#update

and routes.rb

Rails.application.routes.draw do
get 'users/index'
root 'users/index'
resources :users
get 'users/new' => 'users#new'
get 'users/:id/', to: 'users#edit'
get 'users/:id/edit, to: 'users#update'

My guess is I have a problem in my routes, and there should be no need to call a 'update' method, it should do this in the edit_user_path right? OR do I need to call the method? Sorry just confused here between routes and calling methods and how that works with rails. Thank very much for any help.

Rspec Testing : NoMethodError - undefined method 'id' for nil.Nilclass

When I am running rspec testing for a controller in Rails, I get the error "NoMethodError : undefined method 'id' for nil.Nilclass" at the second line.

params[:tag_id] is passed down from the front end, so I can't initialize that. How would I correct this error?

     #enables the id to be a name rather than just a number
    if (params[:tag_id].class) == String && (params[:tag_id]!= "alltags")
       tag_id = Tag.find_by(name: params[:tag_id]).id
    elsif params[:tag_id] == "alltags"
       tag_id = "alltags"
    else
       tag_id = params[:tag_id]
    end

Best way to define Constants in Ruby/ RoR at one place

I have multiple classes (4-5) using same constant value, say PI = 3.14. What is the best way to define that constant at one place in Ruby and in RoR application?

Do I construct one module with given Constant and include in all the classes that are using it?

What are best practices and standard Ruby way?

lundi 6 novembre 2017

Paperclip get image URL or tag - Rails 5 JSON

I have a controller method from which I am getting all products (via Ajax):

def get_products_per_page
    limit = 40
    render json: Product.order('created_at').limit(limit).offset(params[:offset])
end

In the model Product is code for default image (from documentation):

has_attached_file :avatar, styles: { 
            medium: "300x300>", thumb: "100x100>" 
            }, 
default_url: "/images/:style/missing.png"

All products are without images (avatars). When I use Paperclip view helpers it works fine and I get the default image:

<% @products.each do |product|%>
        <li class="row">
            <div class="col-md-1">
                <%= image_tag product.avatar.url %>
            </div>
        </li>
<% end %>

But it not work when I get JSON from controller method products. In the JSON I see :

{
    avatar_file_name: null,
    avatar_content_type: null,
    avatar_file_size: null,
    avatar_updated_at: null
}

Is there way to get avatar (get the URL or URL + image tag, default avatar or none), when I query model Product like this ?

Spawning new threads in Rails 3 / Phusion Passenger

I'm working on a Rails 3 app (running on Phusion Passenger) that is spawning new threads in a method.

Will those threads live in the process that spawned them, or will Passenger create a new process for them to live in? They will live in shared memory space at that point, so any variable sets by Thread One will be seen by Thread Two, right?

jQuery DatePicker not showing the calendar

I am creating a web app using Ruby on Rails. In the reservations form page. i have added jQuery date picker plugin for the start date and the end date. when i click on the start date the calendar doesn't show up even though i have added the jquery-ui-rails gem and the //= require jquery-ui/datepickerhere's in applicaiton.js file. here's my code:

assets/application.js

//
//= require jquery
//= require jquery_ujs
//= require jquery-ui/datepicker
//= require toastr
//= require rails-ujs
//= require_tree .

gemfile

gem 'devise'
gem 'toastr-rails' , '~> 1.0'
gem 'jquery-rails', '~> 4.3', '>= 4.3.1'
gem 'omniauth', '~> 1.7', '>= 1.7.1'
gem 'omniauth-facebook', '~> 4.0'
gem "paperclip", "~> 5.0.0"
gem 'geocoder', '~> 1.3', '>= 1.3.7'
gem 'jquery-ui-rails', '~> 5.0'

views/reservations/_form.html.erb

<div class="panel panel-default">
    <div class="panel-heading">
    <span><i class="fa fa-bolt" style="#ffb00"></i>$<%= @room.price%></span>
    <span class="pull-right">Per Night</span>
    </div>

    <div class="panel-body">
        <%= form_for ([@room, @room.reservations.new])do  |f|%>
        <div class="row">
            <div class="col-md-6">
                <label>Check In</label>
                <%= f.text_field :start_date, readonly: true , placeholder:"Start Date", class:"form-control datepicker"%>
            </div>

            <div class="col-md-6">
                <label>Check Out</label>
                <%= f.text_field :end_date, readonly: true , placeholder:"End Date", class:"form-control datepicker", disabled: true%>
            </div>
        </div>

        <div id="preview" style="display: none">
        <table class="reservation-table">
        <tbody>
            <tr>
                <td>Price</td>
                <td class="text-right"><%= @room.price%></td>
            </tr>

            <tr>
                <td>Night(s)</td>
                <td class="text-right"><span id="reservation_days">X</span></td>
            </tr>

            <tr>
                <td class="total">Total</td>
                <td class="text-right"><span id="reservation_total">$</span></td>
            </tr>
        </tbody>
        </table>
        </div>
            <br/>

            <%= f.submit "Book Now", clasS: "btn btn-normal btn-block"%>
        <%end%>
    </div>
</div>



    <script>

function checkDate(data){
    dmy = date.getDate() + "-" + (date.getMonth()+ 1) + "-" + date.getFullYear();
    return[$.inArray(dmy,unavilableDates) == -1];
}

$(function() {
    unavilableDates = [];

    $.ajax({
        url: '<%= preload_room_path(@room)%>',
        dateTyp: 'json',
        success: function(data){
            $.each(data,function(arrId,arrValue){
                for(var d = new Date(arrValue.start_date);
                d <= new Date(arrValue.end_date); d.setDate(d.getDate() unavilableDates.push($.datepicker.formatDate('d-m-yy'));

            }
        });


        $(function(){
            $('#reservation_start_date').datepicker({
          dateFormat: 'dd-mm-yy',
          minDate: 0,
          maxDate: '3m',
          beforeShowDay: checkDate,
          onSelect: function(selected) {
            $('#reservation_end_date').datepicker("option", "minDate", selected);
            $('#reservation_end_date').attr("disabled", false);
            }
                            });

            $('#reservation_end_date').datepicker ({
                dateFromat: 'dd-mm-yy',
                minDate: 0,
                maxDate: '3m',
                beforeShowDay: checkDate,
                onSelect: function(selected){
                    $('#reservation_start_date'.datepicker("option","maxDate",selected);
                }

            });
}
    });
});
    </script>

layouts/application.html.erb

  <head>
    <title>IGloo</title>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="http://ift.tt/2aHU2x3" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="http://ift.tt/2g6N0YS">
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <link rel="stylesheet" href="http://ift.tt/2cMkdWW">
  </head>

samedi 4 novembre 2017

How to use currently logged in user varible in I18n locale file

I have a Rails app that I want to develop using both English and Japanese locales. Once the user logs in, the :flash displays in English "Logged in as " which is hard coded in to the sessions controller. In Japanese, the username would come first and the grammar would come after words ( としてログインされています), so I wanted to have different messages in the en.yml and jp.yml files.

The problem is that I can't get the logged in user's name to work in the yml files; instead of translating the variable to the currently logged in user, it merely displays the variable as text.

What am I doing wrong?

sessions_controller.rb:

class SessionsController < ApplicationController
  def new
  end

  def create
    @user = User.find_by(email: params[:session][:email].downcase)
    if @user && @user.authenticate(params[:session][:password])
      session[:user_id] = @user.id
      flash[:info] = t(:logged_in_as) # points to translator in .yml file
      # flash[:info] = "logged in as #{@user.name}" works but English only 
      redirect_to @user
    else
      flash[:danger] = t(:login_error) 
      render 'new'
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end`

jp.yml

ja:
  log_in_please: "ログインして下さい"
  logged_in_as: "%{user_name}  としてログインされています"
  login_error: "認証できません。入力された内容が正しくありません。"
  activerecord:
    models:
      users:
        name: user_name

EDIT: Here is the view for sessions:

<h1>Log in</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(:session, url: login_path) do |f| %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

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

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

The model is called 'users' and the user name field is called (drum roll) 'name'.

It works if I refer to #{@user.name} in the controller but can I use the user's name in the yml file?

I have read http://ift.tt/NplSk3 quite a few times but still can't find how to refer to the currently logged in user.

vendredi 3 novembre 2017

Rails 'partial not found' masks underlying error

I encountered a sporadic error, ostensibly because Rails sometimes could not find a partial. However, because of the way the error only showed up in certain cases, I suspected, and then found, a different error underlying it.

My question is whether anyone knows of a reliable way to identify the underlying error in a case like this?

The apparent error:

Rails gave this error when responding to a request for a JSON view new.json.erb:

ActionView::Template::Error (Missing partial insightly_contacts/search_result with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee]}. Searched in:
  * "/path/to/project/app/views"

This was odd for two reasons:

  1. The partial in question is present, and renders happily most of the time.
  2. The partial in question is not of format :json; although new.json.erb is a JSON template obviously, it renders the partial in question like so (specifying :html format):

    form_object.possible_insightly_contacts.map { |insightly_contact|
      {
        id: insightly_contact.id,
        html: render(partial: 'insightly_contacts/search_result', locals: { insightly_contact: insightly_contact }, formats: :html)
      }
    }.to_json.html_safe
    
    

Notes:

  • possible_insightly_contacts returns an ActiveRelation.

  • The error only showed up when the form_object was given certain parameters. Basically it takes a search string, which possible_insightly_contacts uses to build a query; a search on 'x' works, while a search on 'z' gives the missing partial error (these are not placeholders, literally the strings 'x' and 'z' worked/failed respectively!)

  • I inspected both the form_object and the results of possible_insightly_contacts, and there were no errors – the request wasn't failing because of an empty set from possible_insightly_contacts, or something unexpected being returned.

The underlying error:

(Note: in a sense this is irrelevant, the point is just that it wasn't really a 'partial not found' error)

The underlying error was that rendering of another partial further down the rendering hierarchy was failing, because of a logic error which only occurred in certain insightly_contact objects. Hence the error only occurred for certain search string values: they returned an object which triggered an error because of some specific data it held.

My question:

How should I have found the underlying error? In the end I just went through all template / partial / model code that could conceivably be called from the template above, and guessed what might be wrong.

I would expect a regular HTML view which triggered a similar bug in an underlying model to give a proper backtrace, and find the issue that way.

But neither the error reported in the server console, nor the backtrace provided, bore any relation to the real issue here.

Has anyone encountered / solved a similar problem?

Is there a canonical approach to this?

React::ServerRendering::PrerenderError in... Rails 5, React

I am using Rails 5 with react-rails gem. I want to use server-side rendering, but I see this error:

React::ServerRendering::PrerenderError in Home#index

Encountered error "# ExecJS::ProgramError: TypeError: Cannot read property 'serverRender' of undefined" when prerendering Main with {}

This is my /assets/javascripts/application.js:

//= require rails-ujs
//= require jquery
//= require react
//= require react_ujs
//= require_tree .

This is javascripts/components.jsx:

class Main extends React.Component{
    render(){
        return (
            <h1>Hello</h1>
        );
    }
}

and this is the view:

<%= react_component('Main', {}, {prerender: true}) %>

Without prerender option, everything works.

jeudi 2 novembre 2017

missing a template for this request format and variant for shopping cart app

i am creating a simple shopping cart but when i click add to cart i am getting a message error saying OrderItemsController#create is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] i have orderitem route setup and the create.js.erb file setup i dont understand why i am getting this error any solution here my code.


errror message

 "\nrequest.variant: #{request.variant.inspect}"

        raise ActionController::UnknownFormat, message
      elsif interactive_browser_request?
        message = "#{self.class.name}\##{action_name} is missing a template " \
          "for this request format and variant.\n\n" \


orderItem.controller.rb

class OrderItemsController < ApplicationController
    def create
        @order = current_order
        @order_item = @order.order_items.new(order_item_params)
        @order.save
        session[:order_id] = @order.id
    end

    def update
        @order = current_order
        @order_item = @order.order_items.find(params[:id])
        @order_item.update_attributes(order_item_params)
        @order_items = @order.order_items
    end

    def destroy
        @order = current_order
        @order_item = @order.order_items.find(params[:id])
        @order_item.destroy
        @order_items = @order.order_items
    end

    private
        def order_item_params
            params.require(:order_item).permit(:product_id, :quantity)
        end
end


create.js.erb

<% if @order.errors.any? || @order_item.errors.any? %>
    alert("Invalid")
<% else %>
    $(".cart").html("<%= escape_javascript(render 'layouts/cart') %>")
<% end %>


route

Rails.application.routes.draw do
  resources :products
  resources :order_items
  resource :carts, only: [:show]

  root 'welcomes#index'

  devise_for :users
  # For details on the DSL available within this file, see http://ift.tt/GVpneB
end


_cart.html.erb

<%= link_to "#{current_order.order_items.size} items in card and price #{current_order.subtotal}", carts_path %>

Can't mass-assign protected attributes: participant

RoR beginner here. I think I am very close to finish this project but there is this problem.

How can I update the function of a person? And why does the creation work, though?

ActiveModel::MassAssignmentSecurity::Error in PersonsController#update Can't mass-assign protected attributes: participant

I use accepts_nested_attributes_for and the creation works like charme. The error above appears when I try to update attributes of the person. I want to be able to update all the personal data like the city, prename etc. and the function of the person. The function_id is in the participants model.

Note When I comment out the nested attribute it is possible to update all the persons attributes. Only updating the function does not work.

Person model

class Person < ActiveRecord::Base
  attr_accessible :participants_attributes, :organization_id,:title,:prename,:surname,:street,:street_number,:zip_code,:city,:phone,:fax,:email
  has_many :participants
  has_many :trials, through: :participants
  accepts_nested_attributes_for :participants

Participant model

class Participant < ActiveRecord::Base

  belongs_to :trial
  belongs_to :function
  belongs_to :person
  attr_accessible :trial_id, :function_id, :person_id

Person form /views/persons/edit.html.erb

<%= form_for([@trial, @person || @participant]) do |f| %>
...
<div class="tr">
  <div class="th">
    <%= f.label t(:function) %>
  </div>
  <div class="tdsep">:</div>
  <div class="td">
     <%=f.fields_for :participant do |builder|%>
          <%=builder.select :function_id, Function.all.collect {|fu| [fu.g, fu.id]}, prompt: t(:select_function), size: 35%>
          <%=builder.hidden_field :trial_id, value: @trial.id%>
      <%end%>
      </div>
  </div> ...

Person controller

def update
@person = Person.find(params[:id])
authorize! :update, @person

respond_to do |format|
  if @person.update_attributes(params[:person])
    format.html { redirect_to @person, notice: 'Person was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @person.errors, status: :unprocessable_entity }
    end
  end
end

Thank you in advance =)

template.path_without_format_and_extension Not working in rails 3.0.3. Getting undefined method template

I am using i18n in rails 3.0.3 and user have functionality to edit text. If user save text then it comes from database instead of en.yml file. I have override t helper like below:

def c_t(key, options = {})
    c_key = (scope_key_by_partial_custom(key)).gsub(".","_")
    if $LAYOUT_CONTENTS[c_key].present?
      $LAYOUT_CONTENTS[c_key]
    else
      t(key,options)
    end
  end

and then

def scope_key_by_partial_custom(key)
  if key.to_s.first == "."
    template.path_without_format_and_extension.gsub(%r{/_?}, ".") + key.to_s
  else
    key
  end
end

I am calling this method from view:

<h1 <%= c_t '.title' %></h1>

It was working fine in rails 2.3 but after upgrading rails to 3.0.3 I am getting error **undefined method `template' for Class

mercredi 1 novembre 2017

Heroku Not Receiving Seed Data from Rails App

I deployed a Rails App to Heroku and the database migrated fine, except the db/seeds.rb file won't push to Heroku. I've tried running heroku run rake db:seed, as well as all the other solutions suggested online, but nothing is working. Heroku doesn't seem to have access to the seeds.rb file at all.

After running heroku run db:seed, nothing seems to happen of worth:

Running rake db:seed on ⬢ top5application... up, run.1885 (Free)
D, [2017-11-02T05:42:19.665233 #4] DEBUG -- :   
ActiveRecord::SchemaMigration Load (1.3ms)  SELECT 
"schema_migrations".* FROM "schema_migrations"

The Heroku logs also don't seem to contain any useful information:

1d22032e7d7e fwd="69.201.160.131" dyno=web.1 connect=0ms service=17ms status=200 bytes=4542 protocol=https
2017-11-02T05:13:34.409329+00:00 app[web.1]: I, [2017-11-02T05:13:34.409232 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e] Started GET "/lists" for 69.201.160.131 at 2017-11-02 05:13:34 +0000
2017-11-02T05:13:34.410736+00:00 app[web.1]: I, [2017-11-02T05:13:34.410667 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e] Processing by ListsController#index as HTML
2017-11-02T05:13:34.413696+00:00 app[web.1]: D, [2017-11-02T05:13:34.413601 #4] DEBUG -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   [1m[36mList Load (0.9ms)[0m  [1m[34mSELECT "lists".* FROM "lists" ORDER BY average_rating DESC[0m
2017-11-02T05:13:34.415282+00:00 app[web.1]: I, [2017-11-02T05:13:34.415205 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   Rendering lists/index.html.erb within layouts/application
2017-11-02T05:13:34.417088+00:00 app[web.1]: D, [2017-11-02T05:13:34.416900 #4] DEBUG -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   [1m[36mList Load (0.8ms)[0m  [1m[34mSELECT "lists".* FROM "lists" ORDER BY "lists"."created_at" DESC[0m
2017-11-02T05:13:34.418866+00:00 app[web.1]: D, [2017-11-02T05:13:34.418785 #4] DEBUG -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   [1m[36mTopic Load (0.7ms)[0m  [1m[34mSELECT "topics".* FROM "topics"[0m
2017-11-02T05:13:34.419839+00:00 app[web.1]: I, [2017-11-02T05:13:34.419757 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   Rendered lists/index.html.erb within layouts/application (4.3ms)
2017-11-02T05:13:34.422316+00:00 app[web.1]: D, [2017-11-02T05:13:34.422246 #4] DEBUG -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   [1m[36mUser Load (0.9ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
2017-11-02T05:13:34.423714+00:00 app[web.1]: I, [2017-11-02T05:13:34.423652 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e]   Rendered layouts/_logged_in.erb (0.8ms)
2017-11-02T05:13:34.423973+00:00 app[web.1]: I, [2017-11-02T05:13:34.423915 #4]  INFO -- : [44ea0b33-64d7-4516-90d1-1d22032e7d7e] Completed 200 OK in 13ms (Views: 7.0ms | ActiveRecord: 3.3ms)

I'd really appreciate any insight because this is very perplexing.

Is it accurate to say that Python/Django is more explicit than Ruby/Rails in how the components are constructed and connected together?

I've learned quite a bit with Ruby/Rails and am now venturing into learning Python/Django. What I've noticed so far is that I see the connections more clearly with Django than I did with Rails. In Rails, that magic that it has under the hood seems awesome, stuff just works....but I don't know exactly how. With Django, I have to be much more verbose but in having to write things out, I feel I understand the structure and concepts better. I haven't gone deep into Django just yet, so maybe I will hit the same roadblocks with it in the future.

cannot increment same product in cart

i cannot seem to be able to add a method to increment the same product in my app.i am designing an online store, i want to be able to add a product to cart so that the number of the same items in the cart will increment, when i run the program it starts fine, but when i add a product to cart it gives me this error...

ruby 2.4.1p111 (2017-03-22 revision 58053) [i386-mingw32]

C:\Users\COMPUTER>cd desktop

C:\Users\COMPUTER\Desktop>cd trial

C:\Users\COMPUTER\Desktop\trial>cd depot

C:\Users\COMPUTER\Desktop\trial\depot>rails s
=> Booting Puma
=> Rails 5.0.5 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
*** SIGUSR2 not implemented, signal based restart unavailable!
*** SIGUSR1 not implemented, signal based restart unavailable!
*** SIGHUP not implemented, signal based logs reopening unavailable!
Puma starting in single mode...
* Version 3.10.0 (ruby 2.4.1-p111), codename: Russell's Teapot
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started POST "/line_items?product_id=3" for 127.0.0.1 at 2017-11-01 19:32:19 +0100
  ActiveRecord::SchemaMigration Load (1.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by LineItemsController#create as HTML
  Parameters: {"authenticity_token"=>"i1T0s2RDpZMJfxGvhgygNCSXXowIblsp4R+t1rrIOe9NKPkB83qppszYRtmW65uCUPOJyUPPq9p3yVz+pCCvcw==", "product_id"=>"3"}
  Cart Load (1.0ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT ?  [["id", 17], ["LIMIT", 1]]
  Product Load (1.0ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
Completed 500 Internal Server Error in 1005ms (ActiveRecord: 14.0ms)



NoMethodError (private method `add_product' called for #<Cart:0x4de4bb0>):

app/controllers/line_items_controller.rb:29:in `create'
  Rendering C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (223.0ms)
  Rendering C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (44.0ms)
  Rendering C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (7.0ms)
  Rendered C:/Ruby24/lib/ruby/gems/2.4.0/gems/actionpack-5.0.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (11138.2ms)

this is the controller where the code resides.......

class LineItemsController < ApplicationController
  include CurrentCart
  before_action :set_cart, only: [:create]
  before_action :set_line_item, only: [:show, :edit, :update, :destroy]

  # GET /line_items
  # GET /line_items.json
  def index
    @line_items = LineItem.all
  end
  # GET /line_items/1
  # GET /line_items/1.json
  def show
  end

  # GET /line_items/new
  def new
    @line_item = LineItem.new
  end

  # GET /line_items/1/edit
  def edit
  end

  # POST /line_items
  # POST /line_items.json
  def create
    product = Product.find(params[:product_id])  
    @line_item = @cart.add_product(product)

    respond_to do |format|
      if @line_item.save  
        format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
        format.json { render :show, status: :created, location: @line_item }
      else
        format.html { render :new }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end  
  end

  # PATCH/PUT /line_items/1
  # PATCH/PUT /line_items/1.json
  def update
    respond_to do |format|
      if @line_item.update(line_item_params)
        format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
        format.json { render :show, status: :ok, location: @line_item }
      else
        format.html { render :edit }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /line_items/1
  # DELETE /line_items/1.json
  def destroy
    @line_item.destroy
    respond_to do |format|
      format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def line_item_params
      params.require(:line_item).permit(:product_id, :cart_id)
    end
end

this is the cart.rb.......

class Cart < ApplicationRecord
    has_many :line_items, dependent: :destroy
end

def add_product(product)
 current_item = line_items.find_by(product_id: product.id)
  if current_item
   current_item.quantity += 1 
else
   current_item = line_items.build(product_id: product.id)
     end 
     current_item 

here is the index

<p id="notice"><%= notice %></p> 

<h1>Your Pragmatic Catalog</h1> 
<% cache @products do %>
<% @products.each do |product| %> 
<% cache @product do %>
<div class="entry"> 


<h3><%= product.title %></h3> 

<%= image_tag(product.image_url) %>
<%= sanitize(product.description) %>
<div class="price_line"> 

<span class="price"><%= number_to_currency (product.price) %></span> 

<%= button_to 'Add to Cart' , line_items_path(product_id: product.id)%>
</div> 
</div> 
<% end %>
<% end %>
<% end %>