lundi 30 novembre 2015

Deleting comments result as undefined method `comment_path'?

When I tried to delete comments, the comments were not deleted from database and there is also an error undefined method `comment_path'...

_comment.html.erb

 <% if current_user?(comment.user) %>
   <%= link_to "delete", comment, method: :delete %>
 <% end %>

comments_controller.rb

 def destroy
   @comment.destroy
   flash[:success] = "Micropost deleted"
   redirect_to request.referrer || root_url
 end

microposts_controller.rb

 def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
    @comments = @micropost.comments
 end

routes.rb

 resources :microposts do
    resources :comments
 end

Fail to load posts from a certain category

I'm building a website like www.reddit.com. I have Posts which can belong to eight categories. When a user clicks on a certain category, posts belonging to that category will show up. I was able to create the functionality to allow a user to do this and everything was working fine. I then made a search bar using the ransack gem and I got the search functionality working just fine. But now I can no longer click on categories to have the appropriate posts show up. I'm not sure how I messed this up and I have spent a considerable amount of time trying to figure it out. If anyone can point out the problem it would be greatly appreciated, thanks!

Posts Controller:

  def index
    @search_posts = Post.search(params[:q])
    @search_results = @search_posts.result.paginate(:page => params[:page], :per_page => 10)

    if params[:category_id]
      @category = Category.find params[:category_id]
      @posts = @category.posts.paginate(:page => params[:page], :per_page => 10)
    else
      @posts = Post.paginate(:page => params[:page], :per_page => 10)
    end

  end

I feel like it automatically executes the code in the else block but i'm not sure why because there is a params[:category_id] that comes in when I inspect my logs:

Started GET "/categories/7/posts" for ::1 at 2015-12-01 00:00:11 -0500
Processing by PostsController#index as HTML
  Parameters: {"category_id"=>"7"}
  Category Load (0.2ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 7]]
   (0.3ms)  SELECT COUNT(*) FROM "posts"
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts" LIMIT 10 OFFSET 0

Posts#Index View:

<%= search_form_for @search_posts do |f| %>
  <%= f.text_field :title_cont %>
  <%= f.submit "Search" %>
<% end %>

<% if @search_results.any? %>

  <% @search_results.each do |post| %>

    <div id="each_post">
      <p id="post_title"><%= link_to post.title, strip_url(post.url) %></p>
      <p>Submitted <%= time_ago_in_words(post.created_at) %> ago by <%= link_to post.user.name, user_path(post.user) %></p>
    </div>

  <% end %>

  <%= will_paginate @search_results %>

<% else %>

  <% @posts.each do |post| %>

      <div id="each_post">
        <p id="post_title"><%= link_to post.title, strip_url(post.url) %></p>
        <p>Submitted <%= time_ago_in_words(post.created_at) %> ago by <%= link_to post.user.name, user_path(post.user) %></p>
      </div>

  <% end %>

  <%= will_paginate @posts %>

<% end %>

I'm sure this is not the correct way to pass the category id's but I got it working like this:

<%= link_to 'Gadgets', category_posts_path(1) %>
<%= link_to 'Sports', category_posts_path(2) %>
<%= link_to 'Gaming', category_posts_path(3) %>
<%= link_to 'Pics', category_posts_path(4) %>
<%= link_to 'World News', category_posts_path(5) %>
<%= link_to 'Videos', category_posts_path(6) %>
<%= link_to 'Aww', category_posts_path(7) %>
<%= link_to 'Music', category_posts_path(8) %>

Posts is nested under categories:

  resources :categories do
    resources :posts
  end

How can I display comments of microposts with Rails?

Can someone explain me how can I display the comments in User or Static_pages_controller and how can I write the _comments.html.erb for display the comments? Thank you so much for your attention..

comments_controller

def create
  @comment = Comment.new(comment_params.merge(micropost_id: params[:micropost_id], user: current_user))
  if @comment.save
     flash[:success] = "Comment created!"
     redirect_to current_user
 #......
  end

_comment_form

 <%= form_for([micropost, @comment]) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
   <div class="field">
       <%= f.text_area :content %>
   </div>
   <button class="btn" type="submit">
        Create
   </button>
 <% end %>

static_pages_controller

def home
  if logged_in?
     @micropost  = current_user.microposts.build
     @feed_items = current_user.feed.paginate(page: params[:page])
     @comment = Comment.new
  end
end

_micropost.html.erb

 <%= render 'shared/comment_form', micropost: micropost %>

NoMethodError: undefined method `env' for nil:NilClass Rails Fix

I'm having issues now that i've added devise to my web app, theres a few SO questions on this but they just all point to a readme file and don't actually provide any fixes. I've had to include devise helpers as shown below in order to remove an issue saying the authentication method didn't exist

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
 fixtures :all

      # Add more helper methods to be used by all tests here...
  include Devise::TestHelpers
end

If i don't include it i end up with a huge amount of authentication errors:

ActionView::Template::Error: undefined method `authenticate' for nil:NilClass

but if it is included

 NoMethodError: undefined method `env' for nil:NilClass

Simply occurs in different places instead, is there an actual fix?

Thanks!

When I tried to create comment to micropost I have an error as "undefined method `comment_content'"

When I create a comment for micropost I have an error that "undefined method `comment_content'" and there is an problem on @comment.save method.

Please help me to fix the problem. Thank you for your attentions.

comments_controller

def create
  @micropost = Micropost.find(params[:micropost_id])
  @comment = Comment.new(comment_params)
  @comment.micropost = @micropost
  @comment.user = current_user
   if @comment.save
     flash[:success] = "Comment created!"
     redirect_to current_user
   else
     render 'shared/_comment_form'
   end
end

private

def comment_params
  params.require(:comment).permit(:content)
end

_comment_form

<%= form_for([micropost, @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
   <div class="field">
     <%= f.text_area :content %>
   </div>
    <button class="btn" type="submit">
      Create
    </button>
 <% end %>

comment.rb

belongs_to :micropost
belongs_to :user

validates :comment_content, presence: true
validates :user_id, presence: true
validates :micropost_id, presence: true 

static_pages_controller

 def home
  if logged_in?
  @micropost  = current_user.microposts.build
  @feed_items = current_user.feed.paginate(page: params[:page])
  @comment = Comment.new
end
end

_micropost.html.erb

 <%= render 'shared/comment_form', micropost: micropost %>

rails 3 functional test create error

I am new to functional testing in Rails and I cannot figure out why the test of a controller create method that I describe below fails.

I am getting the following error:

ruby -Itest test/functional/sellers_controller_test.rb 
Run options: 

# Running tests:

F.....F

Finished tests in 3.689409s, 1.8973 tests/s, 2.4394 assertions/s.

  1) Failure:
test_should_create_seller(SellersControllerTest) [test/functional/sellers_controller_test.rb:20]:
"Seller.count" didn't change by 1.
<3> expected but was
<2>.

  2) Failure:
test_should_update_seller(SellersControllerTest) [test/functional/sellers_controller_test.rb:39]:
Expected response to be a <:redirect>, but was <200>

7 tests, 9 assertions, 2 failures, 0 errors, 0 skips

I am testing "sellers_controller.rb". Here is my create method:

  def create
    @seller = Seller.new(params[:seller])
    respond_to do |format|
      if @seller.save
        format.html { redirect_to(@seller, :notice => 'Seller was successfully created.') }
        format.xml  { render :xml => @seller, :status => :created, :location => @seller }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @seller.errors, :status => :unprocessable_entity }
      end
    end
  end

in my test file "sellers_controller_test.rb" I have the following:

  setup do
    @seller = sellers(:one)
  end

and

  test "should create seller" do
    assert_difference('Seller.count') do
      post :create, :seller => @seller.attributes
    end

    assert_redirected_to seller_path(assigns(:seller))
  end

Here is my fixture file sellers.yml

one:
  name: MyString1
  website: MyString1
  email: Email1

two:
  name: MyString
  website: MyString
  email: Email2

Comments to Microposts: Create and Delete Comments in Rails ?

When I tried to delete comments, I have an error that "undefined method `destroy' for nil:NilClass"

When I add comment to different microposts;all comments micropost_id is same and display all comments below all microposts.

I will be grateful if someone help me add comments to microposts. I've tried for two weeks this issue and I have NOTHING :(

create_comments.rb

   def change
     create_table :comments do |t|
         t.string :commenter_id
         t.text :body
         t.references :micropost, index: true, foreign_key: true
         t.timestamps null: false
      end

comments_controller.rb

def create
  micropost = Micropost.find_by(params[:id])
  @comment = micropost.comments.build(comment_params)
  @comment.commenter_id = current_user.id
  @comment.save
  redirect_to root_url
end

def destroy
  @comment.destroy
  flash[:success] = "Comment deleted"
  redirect_to request.referrer || root_url
end

_comment.html.erb

     <% @comment.each do |comment| %>
         <p><%= comment.body %></p>
         <span class="timestamp">
             Posted <%= time_ago_in_words(comment.created_at) %> ago.
             <%= link_to "delete", comment, method: :delete %>
         </span>
     <%end%>

_comment_form.html.erb

<%= form_for(Comment.new) do |f| %>
   <p>
     <%= f.text_area :body, :placeholder => "Leave a comment" %>
   </p>
   <p>
     <%= f.submit %>
   </p>
<% end %>

routes.rb

resources :microposts  
resources :comments 

_micropost.html.erb

<li id="micropost-<%= micropost.id %>">
   <%= link_to micropost.user.name, micropost.user %>
   <%= micropost.content %>

    <div id="comments">
         <%= render "comments/comment" %>
    </div>
         <%= render 'shared/comment_form' %>

</li>

microposts_controller.html.erb

 def show
     @micropost = Micropost.find(params[:id])
     @comment = @micropost.comments(params[:id])
 end

static_pages_controller.html.erb

def home
 if logged_in?
   @micropost  = current_user.microposts.build
   @feed_items = current_user.feed.paginate(page: params[:page])
   @comment = Comment.all
 end
end

No implicit conversion of nil into string Ruby Rails

I have some code that accesses an MLS listing service and downloads pictures into AWS. I am getting the error on MLS login. I'm on ruby 2.2.2p95 and rails 3.2.22.

My code:

AWS::S3::Base.establish_connection!(
    :access_key_id => ACCESS_KEY_ID,
    :secret_access_key => SECRET_ACCESS_KEY
  )

  puts 'connected to AWS'

  client = Rets::Client.new({
   login_url: LOGIN_URL,
   username: LOGIN,
   password: PASSWORD,
   version: VERSION
   })

 begin
    client.login
#  rescue => e
#     puts 'Error: ' + e.message
#     exit!
 end

The error:

➜  LiveByTransit git:(master) ✗ rake update_pics --trace
** Invoke update_pics (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute update_pics
66
connected to AWS
rake aborted!
TypeError: no implicit conversion of nil into String
/home/nitrous/code/LiveByTransit/.bundle/gems/nokogiri-1.6.6.3/lib/nokogiri/xml/document.rb:55:in `read_memory'
/home/nitrous/code/LiveByTransit/.bundle/gems/nokogiri-1.6.6.3/lib/nokogiri/xml/document.rb:55:in `parse'
/home/nitrous/code/LiveByTransit/.bundle/gems/nokogiri-1.6.6.3/lib/nokogiri/xml.rb:64:in `parse'
/home/nitrous/code/LiveByTransit/.bundle/gems/rets-0.9.0/lib/rets/parser/error_checker.rb:17:in `check'
/home/nitrous/code/LiveByTransit/.bundle/gems/rets-0.9.0/lib/rets/http_client.rb:20:in `http_get'
/home/nitrous/code/LiveByTransit/.bundle/gems/rets-0.9.0/lib/rets/client.rb:344:in `http_get'
/home/nitrous/code/LiveByTransit/.bundle/gems/rets-0.9.0/lib/rets/client.rb:63:in `login'
/home/nitrous/code/LiveByTransit/lib/tasks/update_pics.rake:45:in `block in <top (required)>'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:240:in `call'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:240:in `block in execute'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:235:in `each'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:235:in `execute'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:179:in `block in invoke_with_call_chain'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:172:in `invoke_with_call_chain'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/task.rb:165:in `invoke'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:150:in `invoke_task'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:106:in `block (2 levels) in top_level'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:106:in `each'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:106:in `block in top_level'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:115:in `run_with_threads'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:100:in `top_level'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:78:in `block in run'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/usr/local/opt/rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-10.4.2/bin/rake:33:in `<top (required)>'
.bundle/binstubs/rake:16:in `load'
.bundle/binstubs/rake:16:in `<main>'
Tasks: TOP => update_pics
➜  LiveByTransit git:(master) ✗ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
➜  LiveByTransit git:(master) ✗ rails -v
Rails 3.2.22

In my code above, you'll see I commented out the error rescue. If I comment back in, the error looks like this:

➜  LiveByTransit git:(master) ✗ rake update_pics --trace
** Invoke update_pics (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute update_pics
66
connected to AWS
Error: no implicit conversion of nil into String
➜  LiveByTransit git:(master) ✗

I've tried this suggestion with no change.

Get location co-ordinate In ruby on rails

I've heard of Geocoder and Geokit but what I know is that they only work if we provide their functions some parameters . either city /country name or location co-ordinates . But what i want is to get my own location either 'Area name' or latitude or longitude in ruby on rails ,with any gem . Don't suggest request.location because it give me localhost address , not my internet ip .so plz suggest anything reasonable because i'm totally freaked out

Cropping an image on rails

I have the following data both in my js file or as a param in rails. Togther there is an image that is to be sent to server, what I want to achieve is to crop the image based on the data such as below. I am not allowed to use gems :) just using ruby/js code if I can manipulate the image already in js side. I am using cropper js which generated the output to me. What should I do to achieve cropping ? {"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1}

How can I fix my migrations? ActiveRecord::Migrator.current_version and db:migrate:status are wrong

I did a mixture of rake db:migrate and doing a pg_restore (Postgres restore from backup).

This got my db out of sync with db:migrate:status. There are columns in my db ahead of where ActiveRecord::Migrator.current_version so when I try to migrate I get PG::DuplicateTable: ERROR: relation "foo_bar" already exists.

How can I reconcile this?

dimanche 29 novembre 2015

How to Get Sendgrid Subscription Tracking Settings using sendgrid_webapi gem?

I need to track subscription settings through Sendgrid using the following request mentioned here http://ift.tt/1Iu5HdH:

GET http://ift.tt/1Q7F705

I am trying to achieve the same using sendgrid_webapi gem using the query_api method.

client = SendGridWebApi::Client.new("user", "pass")
client.query_api("http://ift.tt/1Q7F705", {:data => 1})

which results in

{"errors"=>[{"field"=>nil, "message"=>"authorization required"}]}

I have added proper smtp_user_name and smtp_password, but it still shows the error. What more details need to be provided to get proper authorization?

How to raise if an action method is missing in Rails 3

I learnt from rails 3 rendering view without action that it's possible for a request to handle a request even if there's no public controller method corresponding to the action.

Is it possible in Rails 3 to configure the development environment to automatically raise in such a scenario by modifying config/environments/development.rb to fail if there isn't a public (as opposed to protected or private) controller method corresponding to the action?

samedi 28 novembre 2015

Errors in my haml file in a ruby on rails project

I'm following a tutorial to make a forum! when I wrote this code in the index.html.haml

- @posts.each do |post|
  %h2= post.title
%p 
Published at
= time_ago_in_words(post.created_at)
= link_to "New Post", new_post_path

I got this errors :

app/views/posts/index.html.haml:7: syntax error, unexpected keyword_ensure, expecting keyword_end
app/views/posts/index.html.haml:10: syntax error, unexpected end-of-input, expecting keyword_end

I really need your help!

rake aborted! PG::ConnectionBad: Error on Cloud9 when trying to run rake routes

as the title says, I get this error by making a simple rake routes.

I guess in C9, the default environment in which the commands are run is in production, because this is my Gemfile settings.

group :production do
  gem 'pg'
end

group :development, :test do
  # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
end

And in my linux partition works perfect, so ... how can I make the rake routes run in the development test environment?

Stripe with Rails: Undefined Stripe Card Token

I searched on SoF and found one question which is related but the answer did not help me and when reading the person's problem, it wasn't exactly the same as mine.

I am integrating Stripe into my RoR platform. The error clearly states what is wrong but I do not know how to fix it.

Error below::

Stripe::InvalidRequestError in Users::RegistrationsController#create Snipped Capture of Error Screen

Request response below:

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"wTMt3fOth2wQig2rdoeRuYL9e6hXiWOVQMH8Et+wszUFCUqr8f8+3FxrGYzmEYMukb7Wk8SL0jjDAAnqVP+big==",
 "plan"=>"2",
 "user"=>{"email"=>"test4@example.com",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "stripe_card_token"=>"undefined"}}

So clearly my stripe_card_token is not being defined when submitting the form.

My application.html.rb file has <%= javascript_include_tag "http://ift.tt/KXmU7y", type: 'text/javascript' %> included in the head tag

My user.js file is setup as follows:

/*global Stripe*/

$(document).ready(function(){
    Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
    //watch for a form submission
    $("#form-submit-btn").click(function(event){
        event.preventDefault(); //stop the button from sending form to server
        $('input[type=submit]').prop('disabled', true); //disables the button
        var error = false; //error noti.
        var ccNum = $('#card_number').val(), //just value store variables
            cvcNum = $('#card_code').val(),
            expMonth = $('#card_month').val(),
            expYear = $('card_year').val();

        if (!error){
            //Get the stripe token:
            Stripe.createToken({
                number:ccNum,
                cvc: cvcNum,
                exp_month: expMonth,
                exp_year: expYear,
            }, stripeResponseHandler);
        }
        return false;
    });

    function stripeResponseHandler(status, response){
        var f = $('#new_user');
        var token = response.id;
        f.append('<input type="hidden" name="user[stripe_card_token]" value="' + token + '" />');
        f.get(0).submit(); //submission of form
    }
});

My registrations_controller.rb file has:

class Users::RegistrationsController < Devise::RegistrationsController
    def create
        super do |resource|
            if params[:plan]
                resource.plan_id = params[:plan] #store user based on plan 1 or 2
                if resource.plan_id == 2
                    resource.save_with_payment #for pro
                else
                    resource.save #for basic
                end
            end
        end
    end
end

Additional/New code placed inside user.rb

  attr_accessor :stripe_card_token

  def save_with_payment
    if valid?
      customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
      self.stripe_customer_token = customer.id
      save!
    end
  end

Generated a new migration with the following:

class AddStripeCustomerTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :stripe_customer_token, :string
  end
end

New/Additional code placed inside my application_controller.rb

  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :stripe_card_token, :email, :password, :password_confirmation) }
  end
end

and added the following line to my routes.rb file in-line with devise:

controllers: { registrations: 'users/registrations' }

I also receive the following error inside the console Error 400 - when submitting the form (bad request to http://ift.tt/1Tj8D38)

RubyMine doesnt understand new created .html.erb files

My RubyMine is not recognizing and highliting syntax for new created .html.erb files, it's working however for the files generated before with rails g controller ... ... ...

The thing is that new created .html.erb file is working on localhost, RubyMine is just not highliting the syntax.

Please, see attached picture showing the difference between new created and old .html.erb file:

Screenshot of RubyMine workplace

Heroku Error Deleting a Post in Production: Rails

I am trying to delete a post in my app. It's working fine in localhost but when i pushed to heroku it's not working. I get an error saying "Something went wrong , Please check the logs". Here is my code:

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show,:search]
  before_filter :check_user, only: [:edit,:update,:destroy]




  # GET /posts
  # GET /posts.json

  def search
    if params[:search].present?
    @posts = Post.search(params[:search])
    else
    @posts = Post.all
    end
  end

  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag])
    else
      @posts = Post.all
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @reviews = Review.where(post_id: @post.id)

  end

  # GET /posts/new
  def new
    @post = Post.new
  end


  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

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

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to root_url, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to root_path, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :description,:image,:all_tags)
    end

    def check_user
      if  current_user.id != @post.user_id
      redirect_to root_path , alert: "Sorry this Post belongs to someone else"
    end
    end

end

The Logs

enter image description here

enter image description here

view/posts/index.html.erb

<h3>Posts</h3>
<table class="table">
  <thead>
    <tr>

      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><h4><%=link_to post.title , post%></h4></td>
        <td><%=raw tag_links(post.all_tags)%></td>
          <td><%= link_to 'Edit', edit_post_path(post) %></td>
          <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
    <%end%>
  </tbody>
</table>



<%= link_to 'new post', new_post_path %>

vendredi 27 novembre 2015

Web application could not be started with Ubuntu 14.04, rbenv ruby 2.2.3p

My vps:

  • Ubuntu 14.04

  • rbenv ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]

  • Rails 4.2.4
  • Passenger + Apache

When I deploy a ruby app:

Web application could not be started.

cannot load such file -- bundler/setup (LoadError) /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require' /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:430:in `activate_gem' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:297:in `block in run_load_path_setup_code' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:435:in `running_bundler' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:296:in `run_load_path_setup_code' /usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app' /usr/share/passenger/helper-scripts/rack-preloader.rb:156:in `<module:App>' /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>' /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>' Error ID d999dc5f

how to identify a Associations between models?

I have two models named item and category, one controller named items_controller i want to create two tables for each model, in this each item has one category ,and i want to add the category if the category is not in the list box, which association can be use here?? and want to know the html code for "new.html" also

jeudi 26 novembre 2015

searchkick aggs undefined method `[]' for nil:NilClass

After install and index the products with searchkick i create a aggregation and rails spit out undefined method `[]' for nil:NilClass

Someone by the way knows or can spare a hint why this behavior with searchkick?

thank's

products model:

after_touch :reindex

     searchkick word_start: [:name],
                 suggest: ["name"],
                 highlight: [:name],
        merge_mappings: true, mappings: {
        product: {
          properties: {
            name: {type: "string", analyzer: "keyword", boost: 100},
             id: {type: "long"},
              price: {type: "long"},
              vitrine_id: {type: "long" },
              brand_id: {type: "long" },
              condition_id: {type: "long"},

          }
        }
      }


    def search_data
        {
            name: name,
            price: price,
            vitrine_id: vitrine_id,
            created_at: created_at,
        }
    end


def self.aggs_search(params)
      query = params[:query].presence || "*"
      conditions = {}
      conditions[:price] = params[:price] if params[:price].present?
      products = Product.search query, where: conditions, 
        aggs: [:price], 
        smart_aggs: true, page: params[:page], suggest: true, highlight: true,
        per_page: 10
      products
    end

products controller:

def index
 @products = Product.aggs_search(params)
end

Products aggs view:

<div class="filtro">
    <h2>Price</h2>
   <% if @products.aggs["price"]["terms"].present? %>
         <ul>
        <% @products.aggs["price"]["terms"].each do |filter| %>
          <li><%= link_to "#{filter["term"]} (#{filter["count"]})", "/products?price=#{filter["term"]}" %></li>
        <% end %>
        </ul>
    <% end %>
  </div>

When i tried to create Comments to Micropost I have an error that : No route matches [POST] "/"

Please help me!!! I'm new at Rails programming. I've finished Michael Hartl's "Ruby on Tutorials" book and now I've tried to add comments to microposts but when I tried to post comments, I have an error that "No route matches [POST]".

I can't find what is wrong there?

And also I want to know that my associations is correct between models? (I want to create comments like Facebook comments to posts)

Thank you so much for your attentions.

comments_controller

class CommentsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user,   only: :destroy

def create
    user = User.find_by(params[:id])
    micropost = user.microposts.build(params[:micropost])

    @comment = Comment.new(params[:comment])
    @comment.micropost_id = micropost_id
    @comment.user = current_user

    if @comment.save
      flash[:success] = "Comment created!"
      redirect_to root_url
    else
      render 'static_pages/home'
    end
end
end

comment.html.erb

<h5>Comments<h5>
<div class="comment">
  <% @user.comments.each do |comment| %>
  <p><%= comment.comment %></p>
  <%= time_ago_in_words(comment.created_at) %> ago.
  <%end%>
  </div>

_comment_form.html.erb

<%= form_for :comment do |f| %>

<%= f.text_area :comment_comment, :size => "40x5", placeholder: "Comment..." %>
 <%= f.submit "Post", class: "btn btn-primary" %>
  <span class="picture">
   <%= f.file_field :picture, accept:'image/jpeg,image/gif,image/png' %>
</span>

_micropost.html.erb

<li id="micropost-<%= micropost.id %>">
<%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
<span class="user"><%= link_to micropost.user.name, micropost.user %></span>
<span class="content">
<%= micropost.content %>
<%= image_tag micropost.picture.url if micropost.picture? %>
</span>
<span class="timestamp">
 Posted <%= time_ago_in_words(micropost.created_at) %> ago.
<% if current_user?(micropost.user) %>
  <%= link_to "delete", micropost, method: :delete,
                                   data: { confirm: "You sure?" } %>
   <% end %>
    </span>
  <ol>
        <%= render "comments/comment" %>
      </ol>
      <%= render 'shared/comment_form', micropost: micropost %>
     </li>

create_comment.rb

class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
  t.text :comment
  t.references :user, index: true, foreign_key: true
  t.references :micropost, index: true, foreign_key: true

  t.timestamps null: false
end
add_index :comments, [:user_id, :micropost_id, :created_at]
 end
end

comment.rb

class Comment < ActiveRecord::Base
 belongs_to :user
 belongs_to :micropost
 end

micropost.rb

class Micropost < ActiveRecord::Base
  belongs_to :user
  has_many :comments
 end

user.rb

      class User < ActiveRecord::Base
      has_many :microposts, dependent: :destroy
     has_many :comments
      end

route.rb

      resources :microposts,          only: [:create, :destroy] do
       member do
      resources :comments,            only: [:create, :destroy] 
       end
     end

Rails validates_uniqueness_of old data

I've this validation in a model

validates_uniqueness_of :name

I created a new object with a default name and I save it without problems. After, I destroyed it and when I want to save a new object with the same name I have the following error:

ActiveRecord::RecordInvalid: Validation failed: Name has already been taken

I'm using Rails 3.0.20

Any ideas?

Thanks!

Spec fails due to FactoryGirl-created Devise user failure

  • Rails 3.2.22 (yeah yeah)
  • RSpec 2.99.2 (ditto)
  • FactoryGirl 4.5
  • Devise 3.5.2

Spec fails with:

Failure/Error: let(:user) { create :user }
NoMethodError:
  undefined method `encrypted_password=' for #<User:0x007fc5d15c0550>

And indeed, if I pry at that point, I see this:

[1] pry> User
=> User(id: integer, email: string, crypted_password: string, password_salt: string, etc...

In rails c I see what I expect:

[1] pry> User.new.respond_to?(:encrypted_password=)
=> true
[3] pry(main)> User.new.respond_to?(:crypted_password)
=> false

What's happening here? Why can't I create a user in my factory, and where are my expected methods?

multisite show host in view

I have a one codebase multiple apps setup on heroku. I am trying to display the host on the home page (stati_controller) which works on my main domain: www.domain.hu (env: production, production.rb) but doesn't on the other one: www.domain.co.uk (env: production-uk, production-uk.rb) Debug tells me: nil What am I missing?

Rails.application.default_url_options[:host] = 'www.domain.co.uk'
Rails.application.default_url_options[:host] = 'domain.co.uk'
config.asset_host = 'www.domain.co.uk' - this "kills" the CSS 
config.default_url_options = { host: 'www.domain.co.uk' }
config.default_url_options[:host] = 'domain.co.uk'
config.action_controller.default_url_options = { host: 'www.domain.co.uk' }
config.action_controller.default_url_options = { host: 'domain.co.uk' }
Rails.application.default_url_options = { host: 'domain.co.uk' }
config.action_controller.default_url_options = { host: 'domain.co.uk' }
config.action_controller.default_url_options[:host] = 'domain.co.uk'
host = 'www.domain.co.uk'
  config.action_controller.default_url_options = { host: host }

I also tried this in static_pages_controller.rb - no luck (with or without before-filter):

def default_url_options
    if Rails.env == 'production'
      {:host => "www.domain.hu"}
    elsif Rails.env == 'production-uk'
      {:host => "www.domain.co.uk"}
    else  
      {}
    end
  end 

And authenticate works based on request.host fine so I don't understand (static_pages_controller.rb):

before_filter :authenticate
...
def authenticate
domain = request.host
if domain == 'www.domain.hu' 
authenticate_or_request_with_http_basic do |username, password| username == 'stuff' && password == 'boda'
  end
elsif domain == 'www.domain.co.uk'
authenticate_or_request_with_http_basic do |username, password| username == 'stuff' && password == 'boda'
end
end
end

I have this in production-uk.rb too that works:

host = 'www.domain.co.uk'
config.action_mailer.default_url_options = { host: host }
UPDATE There is one more thing: When I am in the heroku console of the app and write app.host the reply is always "www.example.com"

Thanks for reading!

Ruby on rails rake db:create already exists

I am trying to create a database using rake db:create it errors out saying db already exists.

When I do a rake db:drop it says db does not exist. I have use external to connect to the DB server and indeed the DB does not exist.

Any help is much appreciated.

Regards, Bhaskar

How to implement tiff.js live preview on show.html.erb

I would like to implement a live preview for my tiff files. I load them from a WebService, not locally from app directory. Images and PDF's are loaded correctly until now. These are my sources:

http://ift.tt/1NeiHcJ

http://ift.tt/1Yw9b8x

First I tried to check with a self-written method if its a tiff file. But unfortunately as the result I got a ugly empty iframe box and the download starts automatically.

<div class="col-xs-8">
  <% if @document.is_pdf? %>
    <iframe class="document_preview_pdf" src="<%= download_documents_path(:id => @document.id.to_s, :preview => 1) %>"></iframe>
  <% elsif @document.is_tiff? %>
    <iframe class="document_preview_tiff" src="<%= download_documents_path(:id => @document.id.to_s, :preview => 1) %>"></iframe>
  <% else %>
    <%= image_tag(download_documents_path(:id => @document.id.to_s, :preview => 1), class: "document_preview_img", :alt => '') %>
  <% end %>
</div>

The documentation from tiff.js contains this as "Usage" but I dont know where I should use it.

var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('GET', "url/of/a/tiff/image/file.tiff");
xhr.onload = function (e) {
    var tiff = new Tiff({buffer: xhr.response});
    var canvas = tiff.toCanvas();
    document.body.append(canvas);
};
xhr.send();

For now I just added <script src="http://ift.tt/1NeiJl1"></script> at the bottom of the show.html.erb file. Shell I write a <script>...</script> with the customized "Usage" below the externly loaded tiff.min.js? Have you any idea how I could implement this javascript?

rake aborted! cannot load such file -- mysql2/mysql2 on El Capitan

I have been trying from last 2 weeks to setup my code on Mac. Previously I was using Ubuntu, it was never this difficult to setup code. I have followed almost all tutorials but no luck. Please can anyone guide me on setting up RoR on mac. After following all the tutorials I end up at mysql error only.

rake aborted!
cannot load such file -- mysql2/mysql2
/Users/sahil/Documents/work/ccprod/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require'
/Users/sahil/Documents/work/ccprod/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require'
/Users/sahil/Documents/work/ccprod/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency'
/Users/sahil/Documents/work/ccprod/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require'
/Users/sahil/Documents/work/ccprod/vendor/bundle/ruby/1.9.1/gems/mysql2-0.3.14/lib/mysql2.rb:8:in `<top (required)>'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:76:in `require'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:72:in `each'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:72:in `block in require'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:61:in `each'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler/runtime.rb:61:in `require'
/Users/sahil/.rvm/gems/ruby-1.9.3-p551@global/gems/bundler-1.10.6/lib/bundler.rb:134:in `require'
/Users/sahil/Documents/work/ccprod/config/application.rb:9:in `<top (required)>'
/Users/sahil/Documents/work/ccprod/Rakefile:4:in `<top (required)>'
(See full trace by running task with --trace)

Please let me know if any other information is required.

mercredi 25 novembre 2015

Is cascade possible in existing dtabase?

we have rails application we have added dependent:destroy to delete the dependent record. Some one suggests that if you will use cascade in database it will work more efficiently rather then dependent: :destroy. Can anyone suggest what will be the best way.

I have look in couple of link Option for Cascade Delete for References or On Delete Creating foreign key constraints in ActiveRecord

But did not get we can do cascade in existing database?

PDF upload Ruby on Rails server - DB Postgres

Hello I am trying to store a PDF document in a PostgreSQL database using Ruby Rails. Currently my code looks like this:

DB File:

      '$20151126021922_create_pdf_creates.rb' 

class CreatePdfCreates < ActiveRecord::Migration
  def change
    create_table :pdf_creates do |t|
      t.binary :pdfload

      t.timestamps null: false
    end
  end
end

Model:

    '$pdf_create.rb'

class PdfCreate < ActiveRecord::Base    

end

Controller:

    '$pdf_creates_controller.rb'

class PdfCreatesController < ApplicationController
  before_action :set_pdf_create, only: [:show, :edit, :update, :destroy]

  # GET /pdf_creates
  # GET /pdf_creates.json
  def index
    @pdf_creates = PdfCreate.all
  end

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

  # GET /pdf_creates/new
  def new
    @pdf_create = PdfCreate.new
  end

  # GET /pdf_creates/1/edit
  def edit
  end

  # POST /pdf_creates
  # POST /pdf_creates.json
  def newpdf
    @pdf_create = PdfCreate.new(pdf_create_params)
    respond_to do |format|
      if @pdf_create.save
        format.html { redirect_to @pdf_create, notice: 'Pdf create was successfully created.' }
        format.json { render :show, status: :created, location: @pdf_create }
      else
        format.html { render :new }
        format.json { render json: @pdf_create.errors, status: :unprocessable_entity }
      end
    end
  end

  def create
    @pdf_create = PdfCreate.new(pdf_create_params)
    #data = File.read(Rails.root + "tmp/consent(1).pdf")
    #Document.create pdfload: data 

    respond_to do |format|
      if @pdf_create.save
        format.html { redirect_to @pdf_create, notice: 'Pdf create was successfully created.' }
        format.json { render :show, status: :created, location: @pdf_create }
        format.pdf { send_data @pdf_create.render}

        else
           format.html { render :new }
        #  format.json { render json: @pdf_create.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /pdf_creates/1
  # PATCH/PUT /pdf_creates/1.json
  def update
    respond_to do |format|
      if @pdf_create.update(pdf_create_params)
        format.html { redirect_to @pdf_create, notice: 'Pdf create was successfully updated.' }
        format.json { render :show, status: :ok, location: @pdf_create }
      else
        format.html { render :edit }
        format.json { render json: @pdf_create.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /pdf_creates/1
  # DELETE /pdf_creates/1.json
  def destroy
    @pdf_create.destroy
    respond_to do |format|
      format.html { redirect_to pdf_creates_url, notice: 'Pdf create was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def pdf_create_params
      params.require(:pdf_create).permit(:pdfload)
    end
end

I send a pdf form and the result that is returned is me:

{"id":5,"pdfload":null,"created_at":"2015-11-26T03:24:37.457Z","updated_at":"2015-11-26T03:24:37.457Z"}

What is wrong? Tks

searchkick 400 [searchkick_search] not found

Someone is having this kind of problem with searchkick? i did something wrong? someone can spare a hint?

thank's

controller:

@products = Product.search(params[:query], page: params[:page])

model:

after_touch :reindex

 searchkick mappings: {
    product: {
      properties: {
        name: {type: "string", analyzer: "keyword"}
      }
    }
  }
   def search_data
    as_json only: [:name, :price]
    # or equivalently
    {
      name: name,
      price: price
    }
  end

after_touch :reindex

 searchkick mappings: {
    product: {
      properties: {
        name: {type: "string", analyzer: "keyword"}
      }
    }
  }
   def search_data
    as_json only: [:name, :price]
    # or equivalently
    {
      name: name,
      price: price
    }
  end

[400] {"error":{"root_cause":[{"type":"query_parsing_exception","reason":"[match] analyzer [searchkick_search] not found","index":"products_development_20151125203817235","line":1,"col":89}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"products_development_20151125203817235","node":"f2jvKNboRcGf0NF11yEqyw","reason":{"type":"query_parsing_exception","reason":"[match] analyzer [searchkick_search] not found","index":"products_development_20151125203817235","line":1,"col":89}}]},"status":400}

Rails has_many through association with inheritance issue

If we have 3 models => Customer, User and Thing and another model Owner thats inherits from User and we try create a has_many through association like this:

class Customer < ActiveRecord::Base
 has_many :things, :dependent => :destroy
 has_many :owners, through: :things
end

class Thing < ActiveRecord::Base
 belongs_to :customer, foreign_key: "customer_id"
 belongs_to :owner, foreign_key: "owner_id"
end

class Owner < User
 has_many :things, :dependent => :destroy
 has_many :customers, through: :things
end

Why @owner.things doesn't work for us? It gives undefined method "things" error

How to bootstrap Angular components within a Rails application

I'm currently working in a Rails 3.2 application that we want to migrate into an Angular application. The first step is to bootstrap a single Angular-component into the app and run Angular within the Rails app, and then convert piece by piece.

Anyone sharing the same experience and has some tips?

Ruby on rails : Error while starting server

While starting the server in Ruby on Rails I'm getting this error. What should I do now?

C:\Ruby22\dev\demo>rails server
C:/Ruby22/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.4-x86-mingw32/lib/nokogiri.rb:
29:in `require': cannot load such file -- nokogiri/nokogiri (LoadError)
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.4-x86-mingw32/lib
/nokogiri.rb:29:in `rescue in <top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.4-x86-mingw32/lib
/nokogiri.rb:25:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/loofah-2.0.3/lib/loofah.rb:3:in
`require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/loofah-2.0.3/lib/loofah.rb:3:in
`<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/lib/r
ails-html-sanitizer.rb:2:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/lib/r
ails-html-sanitizer.rb:2:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/sanitize_helper.rb:3:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/sanitize_helper.rb:3:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/text_helper.rb:32:in `<module:TextHelper>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/text_helper.rb:29:in `<module:Helpers>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/text_helper.rb:6:in `<module:ActionView>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/text_helper.rb:4:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_tag_helper.rb:18:in `<module:FormTagHelper>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_tag_helper.rb:14:in `<module:Helpers>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_tag_helper.rb:8:in `<module:ActionView>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_tag_helper.rb:6:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_helper.rb:4:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers/form_helper.rb:4:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers.rb:50:in `<module:Helpers>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers.rb:4:in `<module:ActionView>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.5/lib/action_view
/helpers.rb:3:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/legacy_asset_tag_helper.rb:7:in `<module:LegacyAssetTagHelper>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/legacy_asset_tag_helper.rb:6:in `<module:Rails>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/legacy_asset_tag_helper.rb:4:in `<module:Sprockets>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/legacy_asset_tag_helper.rb:3:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/helper.rb:45:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/helper.rb:45:in `<module:Helper>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/helper.rb:7:in `<module:Rails>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/helper.rb:6:in `<module:Sprockets>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/rails/helper.rb:5:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/railtie.rb:6:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.3/lib/sprock
ets/railtie.rb:6:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass/rails/
railtie.rb:3:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass/rails/
railtie.rb:3:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass/rails.
rb:11:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass/rails.
rb:11:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass-rails.
rb:1:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.4/lib/sass-rails.
rb:1:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:76:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:76:in `block (2 levels) in require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:72:in `each'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:72:in `block in require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:61:in `each'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runti
me.rb:61:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler.rb:13
4:in `require'
        from C:/Ruby22/dev/demo/config/application.rb:7:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s/commands_tasks.rb:78:in `require'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s/commands_tasks.rb:78:in `block in server'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s/commands_tasks.rb:75:in `tap'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s/commands_tasks.rb:75:in `server'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s/commands_tasks.rb:39:in `run_command!'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/railties-4.2.5/lib/rails/command
s.rb:17:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

C:\Ruby22\dev\demo>

mardi 24 novembre 2015

rake assets:precompile is too slow

My website use AngularJs, HAML, coffescript at front end and rails 3.2.13 at backend. Since AngulraJs, it involves a lot of javascript and hence a lot of assets.

So every time I deploy to either staging or production environment rake assets:precompile take too much time(around 16 minutes )(I ran it on already compiled code with no changes).

I have used 'turbo-sprockets-rails3' gem to only recompile changed files, and only compiling once to generate all assets. But rake assets:precompile still takes around 16 minutes alone.

time rake assets:clean RAILS_ENV=staging

real    0m46.418s
user    0m41.340s
sys 0m2.636s

time rake assets:precompile RAILS_ENV=staging

real 13m14.294s

user 13m4.088s

sys 0m9.344s

Please help me reduce assets compilation time. Thanks in advance.

Can't get nested comments to work with ancestry gem

I'm trying to implement replies for my comments in rails. I was watching this video as a guideline http://ift.tt/1nN78vl All the comments I create just becomes the root node, everytime I try replying to a comment it seems like it just doesn't register as the children node. (I've checked with rails console and the column 'ancestry' for the replying comment is always nil)

My comment is a nested resources under the Post Model. I suspect the problem is with the create function in the comments controller?

using rails '4.2.4'

Comments controller:

def new
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build
    @comment.parent_id = params[:parent_id]

end

def create

    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)
    @comment.user = current_user

    if @comment.save
        redirect_to build_post_path(@post)
    else
        redirect_to build_post_path(@post)
    end
end

comments/new.html.erb

    <div class = "row">
        <div class="col-md-8 col-md-offset-2 ">
            <h3>Reply</h3>
            <ol class ="comments">
                <%= render @comment.parent if @comment.parent %>
            </ol>
        </div>
    </div>


    <%= render 'form' %>

comments/_form.html.erb

<div class = "row">
      <div class = "col-md-5 col-md-offset-2">
            <%= form_for([@post, Comment.new]) do |f| %>

                  <%= render 'shared/error_messages',object: f.object %>

                  <%= f.hidden_field :parent_id %>

                  <%= f.label :comment %>
                  <%= f.text_area :comment , class: 'form-control', rows: "4"  %>

                  <div class = "row">
                        <div class = "col-md-3">
                              <%= f.submit "Submit", class: "btn btn-primary" %>
                        </div>
                  </div>
            <% end %>
      </div>
</div>

comments/_comments.html.erb

<li id="comment-<%= comment.id %>">

  <span class="avatar"><%= image_tag(comment.user.avatar.url(:thumb)) %></span>
  <span class="user"><%= link_to comment.user.name, comment.user %> <span class = "timestamp"><%= time_ago_in_words(comment.created_at) %> ago.</span></span>
  <span class="content"><%= comment.comment %></span>
  <span class="options">

    <%= link_to "Index", post_comments_path %> | 

    <%= link_to "Reply", new_post_comment_path(:parent_id => comment) %> |

    <% if current_user?(comment.user) %>
      <%= link_to "Delete", [comment.post, comment], method: :delete,
                                       data: { confirm: "You sure?" } %>
      <%= link_to "Edit", edit_post_comment_path(comment.post, comment) %>
    <% end %>
  </span>

</li>

post/show.html.erb

<div class = "row">
    <div class="col-md-8 col-md-offset-2 ">
        <h3>Comments (<%= @post.comments.count %>)</h3>
        <ol class ="comments">
            <%= nested_messages @post.comments.arrange(:order => :created_at) %>
        </ol>
    </div>
</div>

helper method

def nested_messages(messages)
    messages.map do |message, sub_messages|
      render(message) + content_tag(:div, nested_messages(sub_messages), :class => "nested_messages")
    end.join.html_safe
  end

save name as an unique without change its current case

we have an issue for validation unique column creation

The problem is we have already one field name "Stack Overflow"

Now I am able to check if some one put "Stack Overflow" or "STACK OVERFLOW" or "stack overflow" we don't allow user to create that field.

But when some one put more space between "Stack Overflow" it saves with space it saves with that space so it don't check uniqueness of field.

we are using this code for unique column check

self.unique_columns = self.unique_columns + additional_unique_columns.each_line.collect(&:strip).map(&:downcase).uniq.select{|column| !self.unique_columns.map(&:downcase).include?(column.downcase)}

Can anyone suggest how we can check this type of scenario.

How to embed a chart in email when sending out to using mandrill

I want to give out weekly report as a email to the merchant based on certain data where I want to include the chart. Generally on a website I'm using chartkick to draw the charts, but how do I embed chart in an email. Please help me out.

My model code

def weekly_emailer
  # Some code here
  visits = Visit.group(:created_at).count
end

My view code

<%= line_chart @visits %>

link_to Show page takes me to the index page Rails?

I am trying to have a dashboard in my app that lists all the reviews the user has. The problem that i have is when i click on the post that the user gave a review in , it takes me to the index page of all the posts instead of the show page of the specific post. This is the line of code i am having issue with <td><%= link_to review.post.title , posts_path(@post) %></td> . Here's my code:

views/pages/dashboard.html.erb

<div class="align-left">



<div class="col-md-2">
<h5><%= @user.name %></h5>


</div>
<div class="col-md-5">
<h3>My Posts</h3>

<table class="table table-hover">
      <thead>
        <tr>
          <th>Name</th>
          <th>Created</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
      <% @posts.each do |post| %>
        <tr>
          <td><%= post.title %></td>
          <td><%= time_ago_in_words(post.created_at) %> ago</td>
          <td><%= link_to "Edit", edit_post_path(post) %>|<%= link_to "Destroy", post_path(post), method: :delete %></td>
        </tr>
      <% end %>
      </tbody>
    </table>

</div>

<br>

<h3>My Reviews</h3>
<table class="table table-hover">
      <thead>
        <tr>
          <th>Place</th>
          <th>Created</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
      <% @reviews.each do |review| %>
        <tr>
         <td><%= link_to review.post.title , posts_path(@post) %></td> 
        <td><%= time_ago_in_words(review.created_at) %> ago</td>
        </tr>
      <% end %>
      </tbody>
    </table>
</div>

</div>

the Rake route file

enter image description here

Rails add dynamic attribute on data content helper link

i need to get a ajax tooltip on a dynamic link, so the logic seems to concatenate it. but, still not work, so, someone know a way to do this?

thank's

<%= link_to "Profile", edit_user_path(current_user), :class =>"ttooltip",   :data => {:url => "/users/#{@current_user}/links"}    %>

Berkeley CS169.1 MOOC Rotten Potatoes TDD Rspec Error Movie does not implement:

I am trying to go through the Esaas examples of BerkeleyX CS169.1 MOOC class, TDD example using Rspec. I am stuck with this error when I run rspec on my controller.

My rottenpotatoes/spec/controllers/movies_controller_spec.rb file:

require 'rails_helper'
require_relative '../app/controllers/movies_controller.rb'


RSpec.describe MoviesController, type: :controller do
  describe 'searching TMDb' do
    it 'should call the model method that performs TMDb search' do
      allow(Movie).to receive(:show)
    end
  end

My rottenpotatoes/app/controllers/movies_controller.rb

class MoviesController < ApplicationController

  def show
  end

end

running $ rspec /spec/controllers/movies_controller_spec.rb' gives me the following error:

Failure/Error: allow(Movie).to receive(:show)
       Movie(id: integer, title: string, rating: string, description: text, release_date: datetime, created_at: datetime, updated_at: datetime) does not implement: show

An excerpt of my Gemfile:

ruby '2.2.2'
gem 'rails', '4.2.1'
group :development, :test do
  gem 'sqlite3'
  gem 'rspec-rails', '3.3.2'
  gem 'ZenTest', '4.11.0'
end

group :test do
  gem 'cucumber-rails', :require => false
  gem 'cucumber-rails-training-wheels'
end

Also I really should not need:

require_relative '../app/controllers/movies_controller.rb'

in my rspec file, right?

Ruby, problems comparing strings with UTF-8 characters

I have these 2 UTF-8 strings:

a = "N\u01b0\u0303"
b = "N\u1eef"

They look pretty different but the are the same ones they are rendered:

irb(main):039:0> puts "#{a} - #{b}"
Nữ - Nữ

The a version is the one I have stored in the DB. The b version is the one is coming from the browser in a POST request, I don't know why the browser is sending a different combination of UTF8 characters, and it is not happening always, I can't reproduce the issue in my dev environment, it happens in production and in a percentage of the total requests.

The case is that I try to compare both of them but they return false:

irb(main):035:0> a == b
=> false

I've tried different things like forcing encoding:

irb(main):022:0> c.force_encoding("UTF-8") == a.force_encoding("UTF-8")
=> false

Rails Web services for Android App and Data caching

I am new in rails development. My requirement is to make a web service for Android App and store data for future use. My database will occasionally update so i need store my data in any other table so that any future Web Service call will happen then its first check whether data is updated by comparing stored data. If not it will Serve the stored data. Otherwise It will return the updated data.

See I already mention that i an new in rails development so please help me as beginner and please ignore my English if anything wrong

ActiveRecord::RecordNotFound in CustomersController#new Couldn't find Business without an ID

so I have looked at other instances of this error in other questions on SO and none seem to be helpful. So, my authentication system should allow a Business to sign up, and allow a user to sign up under their business. However, I'm getting a "couldn't find business without ID" error.

class CreateUsers < ActiveRecord::Migration
  def change


    create_table :users do |t|

      t.references :company, foreign_key: true


      t.timestamps
      t.string :first_name
      t.string :last_name

      t.string :email
      t.string :password_digest
      t.string :remember_digest
      t.string :role

    end


class CustomersController < ApplicationController

  def new

    set_business

    @customer = @business.customers.create(user_params)

  end

  def create

    @customer = Customer.new(customer_params)
    @customer.save!
    session[:customer_id] = @customer.id
    redirect_to '/'
  rescue ActiveRecord::RecordInvalid => ex
    render action: 'new', alert: ex.message
  end

  private
  def customer_params

    params.require(:customer).permit(:first_name, :last_name, :business_no, :email, :password_digest, :business_id) 
  end

  def set_business

    @business = Business.find (params[:business_id])

  end



HTML snippet: Customer.new.html.erb

<h1>Sign Up</h1>

      <%= form_for(@customer) do |f| %>
          <%= f.label :first_name %>
          <%= f.text_field :first_name, :placeholder => "First name" %>
          <%= f.label :last_name %>
          <%= f.text_field :last_name, :placeholder => "Last name" %>
          <%= f.label :email %>
          <%= f.email_field :email, :placeholder => "Email" %>
          <%= f.label :company_id %>
          <%= f.collection_select :business_id, Business.all, :id, :name %>
          <%= f.password_field :password_digest, :placeholder => "Password" %>
          <%= f.submit "Create Account", class: "btn-submit" %>
      <% end %>



class Business < ActiveRecord::Base
  has_many :customers

end

class Customer < ActiveRecord::Base
  belongs_to :business
end

How am I supposed to define the @business variable without getting this error so that a user can sign up under their business? I want them to select from a list of available companies on the form, which will then link them in the database when the user signs up. What am I doing wrong? I am very new to Ruby and I may need some good explanation to why this is happening.

thank you for your time :)

validation using real named scopes rails

I have an invoice model with approver_note, po_number and state_type.

I need validations to check:

scope :approver, where(state_type: 3)
scope :po_no, where(state_type: 2)

validates :approver_note, :presence => true, uniqueness: { scope: [:ac_id, :approver]} if: :state_three?
validates :po_number, :presence => true, uniqueness: { scope: [:ac_id, :po_no]} if: :state_two?

def state_three?
    self.state_type==3
end

def state_two?
    self.state_type==2
end

How can I make sure that the uniqueness in approver_note validator is run on selected scope of records. It should validate using records having state_type=3.

I need something in the similar lines of this bug...

http://ift.tt/1OpxLU4

Is this available in rails now? or can we achieve this using custom validation?

Update Attributes For Nested Forms

Hello I'm creating an online retail store.

I have a Category model and a Sizes model. They are nested in a form. When I create a Category I also create sizes for that category.

Right now I can create a Category and sizes. However I can't update the sizes in the nested form.

So click edit category and change the name of one size then click update. I get the below error. On screen it just says "has already been taken".

How do I update sizes through this nested form? /Users/Documents/Safsy/Website/Safsy/Safsy/app/controllers/categories_controller.rb @ line 40 CategoriesController#update:

    39: def update
 => 40:   binding.pry
    41:   if @category.update(category_params)
    42:      redirect_to @category
    43:      flash[:success] = 'Category was successfully updated.'
    44:   else
    45:     render "edit"
    46:   end
    47: end

[1] pry(#<CategoriesController>)>
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameters: _destroy, id
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
   (0.1ms)  begin transaction
  Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1  [["id", 64]]
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XSmall' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Small' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Medium' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Large' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XL' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XXL' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XXXL' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XSmall' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Small' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Medium' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'Large' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XL' LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XXL' LIMIT 1
  Size Exists (0.1ms)  SELECT  1 AS one FROM "sizes" WHERE "sizes"."title" = 'XXXL test' LIMIT 1
  Category Exists (0.1ms)  SELECT  1 AS one FROM "categories" WHERE ("categories"."name" = 'Shorts' AND "categories"."id" != 68) LIMIT 1
   (0.1ms)  rollback transaction

Category Model:

class Category < ActiveRecord::Base
  has_ancestry

  has_many :products
  has_many :sizes

  validates :name, presence: true, length: { maximum: 20 }, uniqueness: true

  accepts_nested_attributes_for :sizes, allow_destroy: true
end

Sizes Model:

class Size < ActiveRecord::Base
    validates :title, presence: true, length: { maximum: 15 }
    validates :title, uniqueness: true

  belongs_to :category
end

Category controller:

class CategoriesController < ApplicationController
  before_action :set_category,   only: [:show, :edit, :update]
  before_action :admin_user,     only: [:destroy, :index, :edit, :show]

  def index
    @categories = Category.all
  end

  def show
    @tags = Product.where(category_id: @category.id).tag_counts_on(:tags)
    if params[:tag]
      @products = Product.tagged_with(params[:tag])
    else
      @products = Product.where(category_id: @category.id).order("created_at DESC")
    end
  end

  def new
    @category = Category.new
    3.times do
      @category.sizes.build
    end
  end

  def edit
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to @category
      flash[:success] = "You have created a new category"
    else
      flash[:danger] = "Your category didn't save"
      render "new"
    end
  end

  def update
    binding.pry
    if @category.update(category_params)
       redirect_to @category
       flash[:success] = 'Category was successfully updated.'
    else
      render "edit"
    end
  end

  def destroy
    category = Category.find(params[:id])
    category.sizes.destroy_all
    category.destroy
    flash[:success] = "Category deleted"
    redirect_to categories_path
  end

  private

  def set_category
    @category = Category.find(params[:id])
  end

  def category_params
    params.require(:category).permit(:name, :parent_id, size_ids: [], sizes_attributes: [:title])
  end
end

Sizes Controller:

class SizesController < ApplicationController
  before_action :logged_in_user, only: [:create, :index, :destroy, :update]
  before_action :admin_user, only: [:create, :index, :destroy, :update]

  def create
    @size = Size.create(size_params)
  end

  def index
    @sizes = Size.all
  end

  def destroy
    Size.find(params[:id]).destroy
  end

  def update
    @size.update_attributes(size_params)
  end

  private

  def size_params
    params.require(:size).permit(:title, :category_id)
  end
end

Here are the params at Category Update method:

    39: def update
 => 40:   binding.pry
    41:   if @category.update(category_params)
    42:      redirect_to @category
    43:      flash[:success] = 'Category was successfully updated.'
    44:   else
    45:     render "edit"
    46:   end
    47: end

[1] pry(#<CategoriesController>)> params
=> {"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"ZHuWURBwIctFJLgZ1HGNeKvGpK8LlgH9S6Mrh7No/CFdjtwNFoNtfi9NIVHBVhApYH/U5tuOzV0eqhSq/95SCw==",
 "category"=>
  {"name"=>"Shorts",
   "parent_id"=>"64",
   "sizes_attributes"=>
    {"0"=>{"title"=>"XSmall", "_destroy"=>"false", "id"=>"21"},
     "1"=>{"title"=>"Small", "_destroy"=>"false", "id"=>"22"},
     "2"=>{"title"=>"Medium", "_destroy"=>"false", "id"=>"23"},
     "3"=>{"title"=>"Large", "_destroy"=>"false", "id"=>"24"},
     "4"=>{"title"=>"XL", "_destroy"=>"false", "id"=>"25"},
     "5"=>{"title"=>"XXL", "_destroy"=>"false", "id"=>"26"},
     "6"=>{"title"=>"XXXL test", "_destroy"=>"false", "id"=>"27"}}},
 "commit"=>"Update Category",
 "controller"=>"categories",
 "action"=>"update",
 "id"=>"68"}

Using Algoliasearch Client JS Angular Module with RequireJS in a Rails Application

Even though the Wiki says it supports all major module loaders, I am unable to figure this one out. Googling is not yielding any helpful results.

I am trying to use algoliasearch-client-js (Angular build) in our existing Rails 3.2 application where in we use RequireJS for AMD support with pre-compilation. I am using requirejs-rails gem and maintaining a requirejs.yml to manage paths config:

image

and this file is under the /vendor directory:

image

I am adding this to the angular module:

var app = angular.module('events', [
        'app.controllers',
        'app.directives',
        'app.filters',
        'app.factories',
        'app.services',
        'ngCookies',
        'algoliasearch'
    ]);

but still it is unable to find this module and looking at a wrong place: enter image description here

This works locally but compiling the assets gives problems. Any pointers to resolve this issue is appreciated.

Display user entered data on contact us form when validation fails in rails?

My controller is :

class ContactController < ApplicationController
     def contact_us
        @cntus = params[:post]
        if @cntus != nil
            @msg="Success"
        end
     end
end

Now when user entered invalid data or email verification failed, data must be present in the form what user had entered.

lundi 23 novembre 2015

The method to redirect from one page to other on ruby on rails

In my code, I use something like:

<li><%= link_to "Find a meal", {:controller =>'microposts', :action => 'index'} %></li> 

to redirect to another page.

When I studied the mailbox part, I mentioned the code is:

<li><%= link_to "Inbox", mailbox_inbox_path %></li>

And this kind of notations appear in other places of this tutorial as well. I thought mailbox_inbox_path is a variable already defined somewhere. But I can't find it.

This is the tutorial of inbox messaging.

Rails run an diferent application to current path

I have two Rails projects (project1: 3.2.11, project2: 4.2.4), whose folders are into the folder called Projects. In the terminal, when current path is /Users/me/Projects/project1 then, run rails s, when I visite localhost:3000, the project launched is the other one: /Users/me/Projects/project2, not the project I start from.

How to completely delete a DB on Ruby on Rails?

I have a small Ruby on Rails app, and I made a mistake creating a model and so on. How can I fully delete its database? Not reseting migrations or dropping its tables, but to delete all db related files? (schema.rb, ....)

Dynamical query: get some (not all) of the has_many associations- with only selected values


Hello, I would like to make a query on users that would preload its addresses but with some conditions.

Simple? users = User.include(:addresses) will work. but I have 2 more conditions to add.

class User < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :user

  attr_accessible :box_number, :name, :content1, :content2, :content3
end

        #example output: [10, 7, 39, 14, 10, 10, 20, 20, 37, 4, 37]
        def get_random_integer_array
          (0..10).collect{ rand(50) } #example ouput: 
        end

    #example ouput: [:name, :content1]
        def get_random_attributes_array
          random_number = rand(3)
          case random_number
            when 0
              [:name]
            when 1
              [:name, :content1]
            when 2
              [:content2]
            else
              [:name, :content1, :content2, :content3]
          end
        end

1) I don't want all addreses. I would like only the addresses which their box_number (integer) will match one of the given dynamic integer array.

random_array =  get_random_integer_array
=> [24, 28, 41, 47, 30, 5, 3, 44, 14, 25, 41]

So like: Address.where(id: random_array) but to 'glue' it to the User's query

2) After that's done. I don't want to addresses to contain their entire attributes, (:name, :content1, :content2, :content3), only a selected few. Again, like Address.select([:name, :content1]) - just 'glue' it to the User query

I have users, each of them has_many addresses. I would like to display all the users in a table, each row is a single user, additionally, that row will contain the user's (selected) addresses

So for example: if random_box_number_array = get_random_integer_array rolled: [3,6,9] and random_attributes = get_random_attributes_array rolled [:name, :content1]

I would like query to match that: meaning users = User.

To summarize: I would like a query on users, which will:

  • load all users, while
  • preloading only the selected addresses for each user, but
  • for the addresses to only contain( so they wouldn't load) the desired attributes.

And to further explain:

users = User.include(:addresses)
first_user = users.first

first_user_addresses = first_user.addresses
first_user_addresses.find_by_box_number (10)
#=> will fetch it 
first_user_addresses.first.content2
#=> will fetch content2



#but
box_numbers = [1,3,5] #not 10
attributes = [:name, :content1] #not content2
users = User.some_magic_query(box_numbers)
first_user = users.first

first_user_addresses = first_user.addresses
first_user_addresses.find_by_box_number (10)
#=> will not find it

#and
first_user_addresses.first.content2
#=> will not find it

Carrierwave image magick convert png as white transparent for android notification icon

I am using carrierwave(Image Magick) to convert a image as white transparent for Android notification icon.

http://ift.tt/wSGUQI

This my image uploader

class IconUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  DIMENSIONS = [48,48]

  process :white_transparent

  def white_transparent
    manipulate! do |img|
      img.combine_options do |cmd|
        cmd.transparent("#ffffff")
        cmd.background "rgba(255,255,255,0.0)"
        cmd.channel "a"
        cmd.separate
        cmd.negate
      end
      img = yield(img) if block_given?
      img
    end
  end

  def filename
    "notification_icon.png"
  end
end

But I am getting the image as 'black on white' instead of "white on black".

This how i want the image enter image description here

Am i missing anything here? Kindly help.

How to avoid a option from select tag

When i am selecting size,i am getting size options like this. i want to avoid size ist option(orange colored background). how to avoid that This is how i get select option

enter image description here

i want to avoid a size from this.

This is my select code. = select_tag "standard_size_id", options_from_collection_for_select(@standard_sizes, "id", "name"), class: ' form-control', prompt: 'Size'

Any help is appreciatable

dimanche 22 novembre 2015

how to give whitespace in ruby slim

I want to seperate currency and total with whitespace.

Please suggest me a solution Any help is appreciatable

p strong Total: span = @order.currency = humanized_money_with_symbol @order.total_paisas/100

Generate .xlsx file in custom specified format

Hell0..! Is there any possibility to generate .xlsx file in custom specified format using HTML,CSS in Jquery/Javascript/Rails,formate is look like thisenter image description here

Loading a bootstrap template to a rails app

I have a template I purchased and I want to use it on my ROR app which uses bootstrap-sass 3.1.1. I put the necessary files in my assets folder and I am trying to use them by putting the following in my view head

<head>
<meta charset="utf-8">
<title>Blah</title>

<!-- Web Fonts -->
<link href='http://ift.tt/1N7eCqL' rel='stylesheet' type='text/css'>
<link href='http://ift.tt/19N7i3B' rel='stylesheet' type='text/css'>
<link href='http://ift.tt/OsMhNH' rel='stylesheet' type='text/css'>
<link href='http://ift.tt/1prVzIU' rel='stylesheet' type='text/css'>

<!-- Bootstrap core CSS -->
<link href="/assets/template/bootstrap/css/bootstrap.css" rel="stylesheet">

<!-- Font Awesome CSS -->
<link href="/assets/template/fonts/font-awesome/css/font-awesome.css" rel="stylesheet">

<!-- Fontello CSS -->
<link href="/assets/template/fonts/fontello/css/fontello.css" rel="stylesheet">

<!-- Plugins -->
<link href="/assets/template/plugins/magnific-popup/magnific-popup.css" rel="stylesheet">
</head>

I cant seem to get the app to use these files like the Bootstrap core CSS. Am I trying to link to it the right way or did I miss something?

Rails partial error missing template even though there is

For some reason the show link throws error while trying to render its partial, even though the partial exists (named _show.html.erb)

Made no changes to the routes file. It simply has the root declaration and resources :notes

And I have not deleted the original "show.html.erb" generated by Scaffold.(matters?)

index.html.erb

<% @notes.each do |note| %>
  <% note.title %>
  <%= link_to 'Show', note, remote: true, class: "note-show" %> 
<% end %>

<div id="note-show">

</div>

_show.html.erb

<% note.title %>
<% note.body %>

show.js.erb

$('#note-show').html("<%= render :partial => 'show' %>");

notes controller

class NotesController < ApplicationController
before_action :set_note, only: [:show, :edit, :update, :destroy]
def index
    @notes = Note.all.order('created_at DESC')
end

def show
    respond_to do |format|               
      format.js
      format.html
    end  
end

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

Error is

ActionView::MissingTemplate in Notes#show

Showing /home/arjun/rails/notes/app/views/notes/show.html.erb where line # raised:
Missing partial notes/_show, application/_show with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/arjun/rails/notes/app/views"
  * "/home/arjun/.rvm/gems/ruby-1.9.1-p431/gems/twitter-bootstrap-rails-3.2.0/app/views"

Strangely on some links it simply shows

$('#note-show').html("hello
");

I found this by using the Browser Page Source

What is incorrect here?

NoMethodError in Pages#dashboard

I am creating a dashboard for my app but when i want to display the reviews i get the NoMethodError although i have defined the variables in the controller. Here's my code

pages_controller.rb

class PagesController < ApplicationController
    before_action :authenticate_user!, only: [:dashboard]

  def about
  end

  def help
  end

  def contact
  end

def dashboard
  @user = current_user
  @places = @user.places
  @reviews = @user.reviews
end

end

reviews_controller.rb

class ReviewsController < ApplicationController
  before_action :set_review, only: [:edit, :update, :destroy]
  before_action :set_place
  before_action :authenticate_user!



  # GET /reviews/new
  def new
    @review = Review.new
  end

  # GET /reviews/1/edit
  def edit
  end

  # POST /reviews
  # POST /reviews.json
  def create
    @review = Review.new(review_params)
    @review.user_id = current_user.id
    @review.place_id = @place.id
    @review.save
    redirect_to place_path(@place)
  end

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

  # DELETE /reviews/1
  # DELETE /reviews/1.json
  def destroy
    @review.destroy
    respond_to do |format|
      format.html { redirect_to reviews_url, notice: 'Review was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

  def set_place    
  unless @place = Place.where(id: params[:place_id]).first
    redirect_to places_path, flash: {alert: "Place doesn't exists"}
  end
end

    # Never trust parameters from the scary internet, only allow the white list through.
    def review_params
      params.require(:review).permit(:comment,:rating)
    end
end

places_controller.rb

class PlacesController < ApplicationController
  before_action :set_place, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show]

  # GET /places
  # GET /places.json
  def index
    @places = Place.all
  end

  # GET /places/1
  # GET /places/1.json
  def show
    @reviews = Review.where(place_id: @place.id)
  end

  # GET /places/new
  def new
    @place = Place.new
  end

  # GET /places/1/edit
  def edit
  end

  # POST /places
  # POST /places.json
  def create
    @place = Place.new(place_params)
    @place.user_id = current_user.id

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

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

  # DELETE /places/1
  # DELETE /places/1.json
  def destroy
    @place.destroy
    respond_to do |format|
      format.html { redirect_to places_url, notice: 'Place was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def place_params
      params.require(:place).permit(:name, :address, :description, :phone, :website)
    end
end

/pages/dashboard.html.erb

<div class="container">
<div class="row">
<div class="col-md-2">


</div>
<div class="col-md-5">
<h3>My Places</h3>

<table class="table table-hover">
      <thead>
        <tr>
          <th>Name</th>
          <th>Created</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
      <% @places.each do |place| %>
        <tr>
          <td><%= place.name %></td>
          <td><%= time_ago_in_words(place.created_at) %> ago</td>
          <td><%= link_to "Edit", edit_place_path(place) %>|<%= link_to "Destroy", place_path(place), method: :delete %></td>
        </tr>
      <% end %>
      </tbody>
    </table>
<%= link_to "New Place", new_place_path %>
</div>


<h3>My Reviews</h3>
<table class="table table-hover">
      <thead>
        <tr>
          <th>Place</th>
          <th>Created</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
      <% @reviews.each do |review| %>
        <tr>
          <td><%= review.place.name %></td>
          <td><%= time_ago_in_words(review.created_at) %> ago</td>
          <td><%= link_to "Edit", edit_review_path(review) %>|<%= link_to "Destroy", review_path(review), method: :delete %></td>
        </tr>
      <% end %>
      </tbody>
    </table>
</div>
</div>
</div>

Did anyone had this issue before ?

Input number multiplies as a string instead of number - Rails 4

I want you to focus on the line conversion = value * 7.50061

Consider the following. When i print the conversion with an initial value of 12, i get seven times 12 like this 12121212121212 . Propably thats because i am multiplying a string but when i tried

value.to_i i had an error saying implicit conversion from float to string??

i submit a value from an input element in the view and i input it from the CalculationsController to the CalculationsHelper

module CalculationsHelper

  # parameter1 = Sa02, parameter2 = Hgb, parameter3  = PaO2
  def AOC(parameter1,parameter2,parameter3,unit_parameter2,unit_parameter3)
    # CaO2 = ( Hgb * 1.34 * SaO2 / 100 ) + ( PaO2 * 0.031 )
    if (unit_parameter3 != "mmHg")
      puts "entered conversions"
      conversions(unit_parameter3,parameter3, "mmHg")
    end
  end

  def conversions(input, value, target)
    if (target == "mmHg")
      if (input == "Kpa")
        puts "this is the value before " + value
        conversion = value * 7.50061
        puts "this is the " + conversion
      end
    end
  end

end

CalculationsController

class CalculationsController < ApplicationController
  include CalculationsHelper

  def index

  end

  def calculation

    if (params["equation"] == "AOC")
      puts "entered AOC"
      AOC(params["parameter1"],params["parameter2"],params["parameter3"],params["unit_parameter2"],params["unit_parameter3"])
    end
    respond_to do |format|
      format.json {
        render json: { success: "ok" }
      }
    end
  end
end

any help appreciated

Issues with Createing a form update button from a controller method in Rails 4

Hey all i am building out a CAD App in Rails 4 Ruby 2.

Background:

I have a form field that is a f.time_select, i would like to replace that with a button that says on scene. When Pressed I would like it to update the unit_on_scene column in my calls table and then redirects me to the show.html.erb page.

My Button Looks Like:

<%= link_to "On Scene", update_unit_on_scene_call_path class: 'btn btn-success btn-sm' %>

My routes.rb Looks Like:

  resources :calls do 
    collection do
      get 'history'
    end
    member do
      patch :update_unit_on_scene
    end
  end

That then gives me this link in Rake Routes:

update_unit_on_scene_call PATCH  /calls/:id/update_unit_on_scene(.:format) calls#update_unit_on_scene

My Controller Method Looks Like:

def update_unit_on_scene
  @call = Call.find(params[:id])
  @call.unit_on_scene = DateTime.now
  @call.save

  respond_to do |format|
    if @call.update(call_params)
      format.html { redirect_to @call, notice: "On Scene Time Successfully Updated. - You Are Now Logged Out Of Service" }
    else
      format.html { render action: 'edit' }
    end
  end
end

The Problem I have right now is that when I Push the button it gives the following error:

No route matches [GET] "/calls/3/update_unit_on_scene"

as if it is looking for another page??

Any help would be greatly appreciated as I have never ventured down this road before.

Thanks.

EDIT # 1:

Associated Warning when Button Clicked:

ActionController::ParameterMissing in CallsController#update_unit_on_scene
param is missing or the value is empty: call

Extracted source (around line #107):
105
106
107
108
109
110

    # Never trust parameters from the scary internet, only allow the white list through.
    def call_params
      params.require(:call).permit(:call_time, :status, :primary_type, :secondary_type, :site, :address, :unit_1, :unit_2, :unit_3, :unit_4, :call_details, :unit_on_scene, :unit_clear, :call_num, :site_id, :user_id, :unit2_os, :unit2_cl, :unit3_os, :unit3_cl, :unit4_os, :unit4_cl)
    end
end

Server Log:

Started PATCH "/calls/3/update_unit_on_scene" for ::1 at 2015-11-22 01:38:49 -0700
      ActiveRecord::SchemaMigration Load (0.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"
    Processing by CallsController#update_unit_on_scene as HTML
      Parameters: {"authenticity_token"=>"hH4juJAS7bxs+HHPjSuEDLpucwAh2i2QODH8DvF3JQVxhzhet1AcAs6xzib6AezrlLJ3yZrHLea5ey8206gIqA==", "id"=>"3"}
      Call Load (0.4ms)  SELECT  "calls".* FROM "calls" WHERE "calls"."id" = $1 LIMIT 1  [["id", 3]]
       (0.1ms)  BEGIN
      SQL (0.6ms)  UPDATE "calls" SET "unit_on_scene" = $1, "updated_at" = $2 WHERE "calls"."id" = $3  [["unit_on_scene", "2015-11-22 08:38:50.027783"], ["updated_at", "2015-11-22 08:38:50.031354"], ["id", 3]]
       (6.4ms)  COMMIT
    Completed 400 Bad Request in 48ms (ActiveRecord: 9.9ms)

    ActionController::ParameterMissing (param is missing or the value is empty: call):
      app/controllers/calls_controller.rb:107:in `call_params'
      app/controllers/calls_controller.rb:89:in `block in update_unit_on_scene'
      app/controllers/calls_controller.rb:88:in `update_unit_on_scene'


      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (9.0ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.2ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.5ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (53.4ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.6ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.6ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.7ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.9ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (42.8ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.8ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.6ms)
      Rendered /Users/TaurenLTD1/.rvm/gems/ruby-2.2.0/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (96.0ms)