samedi 31 octobre 2015

Trying to customize devise views in Rails

So, basically I have 2 users in my app, they are Company and Establishment.

The problem is that I want to customize the edit view for each one of them, but edit_company_registration and edit_establishment_registration are rendering views/devise/registrations/edit.html.erb instead of views/company/registrations/edit.html.erb and views/establishment/registrations/edit.html.erb respectively, so I can't customize each one of them separately, and in addition to that problem whenever I try to edit a record (Company or Establishment) I get this error.

enter image description here

I don't know why is this happening (and I obviously fill all the fields), I don't know if this is part of the effect of the above (the fact that links to edit_company_registration and edit_establishment_registration are rendering views/devise/registrations/edit.html.erb).

Telling a little what I did, I used this command:

rails generate devise:views

To have the views of devise in app/views/company and app/views/admin like this:

enter image description here

But as I said, if I try to go to edit_establishment_registration or edit_company_registration it will render devise/registrations#edit instead of establishment/registrations/edit.html.erb and company/registrations/edit.html.erbrespectively, how can I fix this (or these) problem?, I need help please.

If you are little confused, this is what I want to do:

  1. Be able to customize each edit view separately, for this I guess I have to somehow make it render views/establishment/registrations/edit.html.erb from edit_establishment_registration (same case for company).
  2. Fix the problem that tells me that the password can't be blank (Maybe it's a side effect of the fact that both edit_company_registration and edit_establishment_registration are rendering views/devise/registrations/edit.html.erb, I don't know).

Greetings.

Simple Mongoid typecast and update_attributes validation fails

I am trying to cast fields on mongoid documents. As you can see I am use float for my field When I update a persisted entry with a string, it overwrites my field with a zero value, which should stay the same. But more interesting is, that mongoid says true...

class Product
  include Mongoid::Document

  field :net_price, type: Float # cast for float not string
end

p = Product.create(net_price: 123.45)
# => #<Product _id: 5634bb2b34257be5e2000001, net_price: 123.45>

p.update_attributes!({net_price: "A String"})
# true

p.reload
# => #<Product _id: 5634bb2b34257be5e2000001, net_price: 0.0>

vendredi 30 octobre 2015

current_user method with devise from the console

rails 3.2.18
devise

I started up the rails console:

rails c

Then I logged in:

[17] pry(main)> ApplicationController.allow_forgery_protection = false
=> false
[18] pry(main)> app.post('/sign_in', {"user"=>{"login"=>"somemail@gmail.com", "password"=>"xxxxxxx"}})
=> 302

At this point, shouldn't the current_user method work? When I do:

current_user.id

I get:

NameError: undefined local variable or method `current_user' for main:Object

Sending variables to embedded Ruby/ Ruby on Rails

Lets say I wanted to make a function to return someone's age from a rails database.

function getName(name_input) {
return <%= Names.find_by(name: name_input).age %>
}

When I've tried similary functions is seems that rails doesn't have access to local variables. Is there a workaround?

How to convert rails3 routes into rails4

I have following rails3 routes that I want to convert into rails4.

map.with_options(:conditions => {:subdomain => AppConfig['admin_subdomain']}) do |subdom|
  subdom.root :controller => 'subscription_admin/subscriptions', :action => 'index'
  subdom.with_options(:namespace => 'subscription_admin/', :name_prefix => 'admin_', :path_prefix => nil) do |admin|
    ...
  end
end

Deleting Nested Reviews Deletes the whole Post Created

I am setting a nested review scaffold inside the Post scaffold however, when i try to delete a review that is nested inside the show page in the Post, The whole post is deleted. how can i delete only the reviews without the post?

here's my code:

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show]
  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 posts_url, 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

routes.rb

Rails.application.routes.draw do

  devise_for :users
    resources :posts do
      collection do
        get 'search'
  end
      resources :reviews , except: [:show,:index] do
    member do
      get "like" => "reviews#upvote"
      get "dislike" => "reviews#downvote"
    end
  end

end
  get 'pages/help'

  get 'pages/blog'

  get 'pages/contact'
  get 'pages/tour'

  resources :posts
  root 'posts#index'

  get 'tags/:tag', to: 'posts#index', as: "tag"
end

reviews_controller.rb

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

  respond_to :html



  def new
    @review = Review.new
    respond_with(@review)
  end

    def edit
    end


  def create
    @review = Review.new(review_params)
    @review.user_id = current_user.id
    @review.post_id = @post.id
    @review.save
    redirect_to post_path(@post)


  end

  def update
    @review.update(review_params)
    respond_with(@post)
  end

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

  def upvote
    @review.upvote_from current_user
    redirect_to :back
  end

  def downvote
    @review.downvote_from current_user
    redirect_to :back
  end




  private
    def set_review
      @review = Review.find(params[:id])
    end

    def set_post
      unless @post = Post.where(id: params[:post_id]).first
        redirect_to posts_path, flash: {alert: "Post doesn't exists"}
      end
    end

    def review_params
      params.require(:review).permit(:comment)
    end
end

models/review.rb

class Review < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
  belongs_to :post
end

models/post.rb

class Post < ActiveRecord::Base
  searchkick
  has_many :reviews , dependent: :destroy
  has_many :taggings
  has_many :tags, through: :taggings
  #Paperclip Installation
  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]


  def all_tags=(names)
  self.tags = names.split(",").map do |name|
      Tag.where(name: name.strip).first_or_create!
  end
end

def all_tags
  self.tags.map(&:name).join(", ")
end

def self.tagged_with(name)
  Tag.find_by_name!(name).posts
end

end

views/posts/index.html.erb

<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 %>

views/posts/show.html.erb

<div class="center">
    <div class="right-align">
      <h2><%= @post.title %></h2>
      <hr>
    </div>

    <%if @post.image.exists?%>
    <%= image_tag @post.image.url(:medium) %>
    <%end%>

    <div class="right-align">
      <%=  markdown @post.description %>

    <br>

    <table class="table table-bordered">
      <tbody>
        <% @reviews.each do |review|%>
        <tr>
        <td >
          Welcome back <%= current_user.name %>
          <h4><%= link_to "like" ,like_post_review_path(@post, review) , class: " btn btn-primary glyphicon glyphicon-chevron-up"%></h4>
          <p><%= review.get_upvotes.size%></p>
          <p><%= review.get_downvotes.size%></p>
          <h4><%= link_to "Dislike" , dislike_post_review_path(@post, review)  , class: "btn btn-primary glyphicon glyphicon-chevron-down"%></h4>
        <p><%=  markdown review.comment %></p>
        <p><%= link_to "Edit", edit_post_review_path(@post, review) %></p>
        <p><%= link_to 'Destroy', @review, method: :delete, data: { confirm: 'Are you sure?' } %></p>




        </td>
      </tr>
        <%end%>


      </tbody>
    </table>




    <p><%= link_to 'Write Review', new_post_review_path(@post) , class: "btn btn-primary" %></p>


    <%= link_to 'Edit', edit_post_path(@post) %> |
    <%= link_to 'Back', posts_path %>

    </div>

</div>

Custom email validator with devise

I followed the twiki to add a custom email validator with devise. It works but the errors are printed twice once for each validation like below. How to fix this? Error message!

Rails Big Blue Button

Is there any stable version for Big blue button on rails 3 ?

I am using http://ift.tt/1MxoRX0 for rails and I started getting errors. Although I have fixed few but I got struck in the following error which is related to I18n. Suggest me necessary changes.

ArgumentError in Bigbluebutton::RoomsController#join

uncaught throw :exception Rails.root: /home/cnt/rails_proje/begalileo

Application Trace | Framework Trace | Full Trace i18n (0.6.1) lib/i18n/backend/base.rb:37:in throw' i18n (0.6.1) lib/i18n/backend/base.rb:37:intranslate' config/initializers/i18n_missing_translations.rb:29:in block in <top (required)>' i18n (0.6.1) lib/i18n.rb:297:incall' i18n (0.6.1) lib/i18n.rb:297:in handle_exception' i18n (0.6.1) lib/i18n.rb:159:in translate' bigbluebutton_rails (1.4.0) app/models/bigbluebutton_room.rb:382:in require_server' bigbluebutton_rails (1.4.0) app/models/bigbluebutton_room.rb:135:in fetch_is_running?' bigbluebutton_rails (1.4.0) app/controllers/bigbluebutton/rooms_controller.rb:272:in join_check_can_create' activesupport (3.2.13) lib/active_support/callbacks.rb:517:in _run__3421418821076967831__process_action__2842134084775200396__callbacks' activesupport (3.2.13) lib/active_support/callbacks.rb:405:in __run_callback' activesupport (3.2.13) lib/active_support/callbacks.rb:385:in_run_process_action_callbacks' activesupport (3.2.13) lib/active_support/callbacks.rb:81:in run_callbacks' actionpack (3.2.13) lib/abstract_controller/callbacks.rb:17:inprocess_action' actionpack (3.2.13) lib/action_controller/metal/rescue.rb:29:in process_action' actionpack (3.2.13) lib/action_controller/metal/instrumentation.rb:30:inblock in process_action' activesupport (3.2.13) lib/active_support/notifications.rb:123:in block in instrument' activesupport (3.2.13) lib/active_support/notifications/instrumenter.rb:20:ininstrument' activesupport (3.2.13) lib/active_support/notifications.rb:123:in instrument' actionpack (3.2.13) lib/action_controller/metal/instrumentation.rb:29:inprocess_action' actionpack (3.2.13) lib/action_controller/metal/params_wrapper.rb:207:in process_action' activerecord (3.2.13) lib/active_record/railties/controller_runtime.rb:18:in process_action' actionpack (3.2.13) lib/abstract_controller/base.rb:121:in process' actionpack (3.2.13) lib/abstract_controller/rendering.rb:45:inprocess' actionpack (3.2.13) lib/action_controller/metal.rb:203:in dispatch' actionpack (3.2.13) lib/action_controller/metal/rack_delegation.rb:14:in dispatch' actionpack (3.2.13) lib/action_controller/metal.rb:246:in block in action' actionpack (3.2.13) lib/action_dispatch/routing/route_set.rb:73:incall' actionpack (3.2.13) lib/action_dispatch/routing/route_set.rb:73:in dispatch' actionpack (3.2.13) lib/action_dispatch/routing/route_set.rb:36:in call' journey (1.0.4) lib/journey/router.rb:68:in block in call' journey (1.0.4) lib/journey/router.rb:56:ineach' journey (1.0.4) lib/journey/router.rb:56:in call' actionpack (3.2.13) lib/action_dispatch/routing/route_set.rb:612:incall' rack-pjax (0.7.0) lib/rack/pjax.rb:12:in call' omniauth (1.2.2) lib/omniauth/strategy.rb:186:incall!' omniauth (1.2.2) lib/omniauth/strategy.rb:164:in call' omniauth (1.2.2) lib/omniauth/strategy.rb:186:incall!' omniauth (1.2.2) lib/omniauth/strategy.rb:164:in call' omniauth (1.2.2) lib/omniauth/strategy.rb:186:incall!' omniauth (1.2.2) lib/omniauth/strategy.rb:164:in call' omniauth (1.2.2) lib/omniauth/builder.rb:59:incall' bullet (4.7.1) lib/bullet/rack.rb:10:in call' warden (1.2.3) lib/warden/manager.rb:35:inblock in call' warden (1.2.3) lib/warden/manager.rb:34:in catch' warden (1.2.3) lib/warden/manager.rb:34:incall' actionpack (3.2.13) lib/action_dispatch/middleware/best_standards_support.rb:17:in call' rack (1.4.5) lib/rack/etag.rb:23:incall' rack (1.4.5) lib/rack/conditionalget.rb:25:in call' actionpack (3.2.13) lib/action_dispatch/middleware/head.rb:14:incall' remotipart (1.2.1) lib/remotipart/middleware.rb:27:in call' actionpack (3.2.13) lib/action_dispatch/middleware/params_parser.rb:21:incall' actionpack (3.2.13) lib/action_dispatch/middleware/flash.rb:242:in call' rack (1.4.5) lib/rack/session/abstract/id.rb:210:incontext' [1]: http://ift.tt/1MxoRX0

Rails: multiple submit button outside simple form

Say I have an Article model, and in the Article model 'settings' view I have two submit buttons outside of a form, "update Details" and "Next Template".

My question is how can I know which button is clicked in the controller. Both submit button is outside of a simple form. I tried like:

 <%= f.submit "update Details",name: "update_details", class: "x-update" %>


<%= f.submit 'Next Template', name: "next_template", class: "x-next" %>

and the logic is the same on the controller

   if params[:update_details]
      [..]
   elsif params[:next_template]
      [..]
   end

but it doesn't work. How do I do that? I can't change the route, so is there a way to send a different variable that gets picked up by [:params]?

How to write prompt to set default select option

I want to display default select option as "select Size" here. how to give in this select option.

Any help is appreciated.

this is my slim file

= select_tag "standard_size_id", options_from_collection_for_select(@standard_sizes, "id", "name"), include_blank: true, class: 'form-control'

jeudi 29 octobre 2015

Updating multiple documents on nested object change

I am using the elasticsearch-rails and elasticsearch-model gems for my Ruby on Rails app, which is like a question-and-answer site.

I have one index my_index and mappings for question, and answer. In particular, question has a nested object with a user:

"question": {
   "properties": {
      "user": {
         "type": "nested",
         "properties": {
            "created_at": {
               "type": "date",
               "format": "dateOptionalTime"
            },
            "name": {
               "type": "string"
            },
            "id": {
               "type": "long"
            },
            "email": {
               "type": "string"
            }
          }
      }
      ...
   }
}

It's possible for a user to change his name, and I have hooks to update the user in Elasticsearch:

after_commit lambda { __elasticsearch__.index_document},  on: :update

But this isn't updating the appropriate question objects correctly, and I don't know what to pass to the index_document call to make sure it updates all the corresponding questions with the new user name. Does anyone know? It might even help me to see what a RESTful/curl request should look like?

Any help would be appreciated!

How to modify as_indexed_json values to run Ruby code

I am trying to import my data using the elasticsearch-rails and elasticsearch-model gems.

Here's what I have in my question.rb:

belongs_to :user

...

def as_indexed_json(options={})
  as_json(
    user_name: user.name,
    user_email: user.email
  )
end

When I run the import Question.import, I get this error:

NoMethodError: undefined method `name' for nil:NilClass

How do I import my data in a way that allows me to run some ruby against the ActiveRecord object? There are other nested associations that are 2 or 3 degrees away, and I would like to denormalize that data in Elasticsearch.

I can't use a transform on the import because that will only work at import time. I need the code to run on create and update events too.

How to search multiple generations in Elasticsearch

Elasticsearch's article outlines how to find objects based on a search through one generation: http://ift.tt/1FanGXd

GET /company/country/_search
{
  "query": {
    "has_child": {
      "type": "branch",
      "query": {
        "has_child": {
          "type": "employee",
          "query": {
            "match": {
              "hobby": "hiking"
            }
          }
        }
      }
    }
  }
}

What if I want to also want to query the branch for the name starting with "liverpool"? How do you modify this search to find that? I keep getting format errors and I can't seem to find information about how nest the queries online.

Ckeditor upload image functionallity disappeared? - Rails

I have installed ckeditor and for a while it had image upload functionality but now it seem absent.

Is there something that i do not know?

I am using carrierwave + minimagick, i also have rmagick installed for another part of the site. i do not think that these two correlate?

ruby script/server error /config/initializers/siteman.rb:23:in `chdir': No such file or directory - project_folder/presents (Errno::ENOENT)

I am using ruby 1.9.3 rails 2.3.18 when I am running rails server by typing ruby script/server then got this error.... Please have a look for Error

Latitude-3540:/var/www/html/siteman$ ruby script/server

  1. NOTE: Gem.source_index is deprecated, use Specification. It will be removed on or after 2011-11-01. Gem.source_index called from /var/www/html/siteman/vendor/rails/railties/lib/rails/gem_dependency.rb:21. config.gem: Unpacked gem ihunter-whatcounts-0.4.0 in vendor/gems has a mismatched specification file. Run 'rake gems:refresh_specs' to fix this. /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/inflector.rb:3:in <top (required)>': iconv will be deprecated in the future, use String#encode instead. => Booting WEBrick => Rails 2.3.18 application starting on http://0.0.0.0:3000 config.load_paths is deprecated and removed in Rails 3, please use autoload_paths instead config.load_paths= is deprecated and removed in Rails 3, please use autoload_paths= instead [FSTR] Using Red Five FileStorage version 0.1 /var/www/html/siteman/config/initializers/siteman.rb:23:inchdir': No such file or directory - /var/www/html/siteman/presents (Errno::ENOENT) from /var/www/html/siteman/config/initializers/siteman.rb:23:in <top (required)>' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:171:in load' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:171:in block in load_with_new_constant_marking' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:547:in new_constants_in' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:171:in load_with_new_constant_marking' from /var/www/html/siteman/vendor/rails/railties/lib/initializer.rb:622:in block in load_application_initializers' from /var/www/html/siteman/vendor/rails/railties/lib/initializer.rb:621:in each' from /var/www/html/siteman/vendor/rails/railties/lib/initializer.rb:621:in load_application_initializers' from /var/www/html/siteman/vendor/rails/railties/lib/initializer.rb:176:in process' from /var/www/html/siteman/vendor/rails/railties/lib/initializer.rb:113:in run' from /var/www/html/siteman/config/environment.rb:9:in <top (required)>' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:182:in require' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:182:in block in require' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:547:in new_constants_in' from /var/www/html/siteman/vendor/rails/activesupport/lib/active_support/dependencies.rb:182:in require' from /var/www/html/siteman/config.ru:2:inblock in ' from /var/www/html/siteman/vendor/bundle/ruby/1.9.1/gems/rack-1.1.6/lib/rack/builder.rb:46:in instance_eval' from /var/www/html/siteman/vendor/bundle/ruby/1.9.1/gems/rack-1.1.6/lib/rack/builder.rb:46:in initialize' from /var/www/html/siteman/config.ru:1:in new' from /var/www/html/siteman/config.ru:1:in' from /var/www/html/siteman/vendor/rails/railties/lib/commands/server.rb:78:in eval' from /var/www/html/siteman/vendor/rails/railties/lib/commands/server.rb:78:in ' from script/server:3:in require' from script/server:3:in'

Carrierwave_backgrounder and delayed_job not working on Heroku: No such file or directory

I am using the Carrierwave_backgrounder, delayed_job and daemons gem to handle uploading multiple images on my application without stealing bandwidth from other users immediately. The worker will run with no issues on my local development server. After pushing to my Heroku staging environment I receive these errors while attempting to complete the jobs.

  Delayed::Backend::ActiveRecord::Job Load (2.5ms)  UPDATE "delayed_jobs" SET locked_at = '2015-10-28 23:46:15.299335', locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-10-28 23:46:15.298692' AND (locked_at IS NULL OR locked_at < '2015-10-28 19:46:15.298734') OR locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=20) RUNNING
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=20) RUNNING
  VehicleImage Load (0.7ms)  SELECT  "vehicle_images".* FROM "vehicle_images" WHERE "vehicle_images"."id" = $1 LIMIT 1  [["id", 91]]
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=20) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-5608/Cancer_show_031.JPG
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=20) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-5608/Cancer_show_031.JPG
   (0.6ms)  BEGIN
  SQL (0.8ms)  UPDATE "delayed_jobs" SET "attempts" = $1, "run_at" = $2, "locked_at" = $3, "locked_by" = $4, "updated_at" = $5 WHERE "delayed_jobs"."id" = $6  [["attempts", 5], ["run_at", "2015-10-28 23:56:45.308678"], ["locked_at", nil], ["locked_by", nil], ["updated_at", "2015-10-28 23:46:15.310442"], ["id", 20]]
   (1.4ms)  COMMIT
  Delayed::Backend::ActiveRecord::Job Load (2.0ms)  UPDATE "delayed_jobs" SET locked_at = '2015-10-28 23:46:15.318187', locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-10-28 23:46:15.317874' AND (locked_at IS NULL OR locked_at < '2015-10-28 19:46:15.317891') OR locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=21) RUNNING
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=21) RUNNING
  VehicleImage Load (0.7ms)  SELECT  "vehicle_images".* FROM "vehicle_images" WHERE "vehicle_images"."id" = $1 LIMIT 1  [["id", 92]]
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=21) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-0693/Cancer_show_033.JPG
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=21) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-0693/Cancer_show_033.JPG
   (0.6ms)  BEGIN
  SQL (1.2ms)  UPDATE "delayed_jobs" SET "attempts" = $1, "run_at" = $2, "locked_at" = $3, "locked_by" = $4, "updated_at" = $5 WHERE "delayed_jobs"."id" = $6  [["attempts", 5], ["run_at", "2015-10-28 23:56:45.322803"], ["locked_at", nil], ["locked_by", nil], ["updated_at", "2015-10-28 23:46:15.324371"], ["id", 21]]
   (1.5ms)  COMMIT
  Delayed::Backend::ActiveRecord::Job Load (2.2ms)  UPDATE "delayed_jobs" SET locked_at = '2015-10-28 23:46:15.329835', locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-10-28 23:46:15.329385' AND (locked_at IS NULL OR locked_at < '2015-10-28 19:46:15.329409') OR locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=22) RUNNING
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=22) RUNNING
  VehicleImage Load (0.9ms)  SELECT  "vehicle_images".* FROM "vehicle_images" WHERE "vehicle_images"."id" = $1 LIMIT 1  [["id", 93]]
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=22) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-8474/Cancer_show_034.JPG
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] Job CarrierWave::Workers::StoreAsset (id=22) FAILED (4 prior attempts) with Errno::ENOENT: No such file or directory - /app/public/uploads/tmp/1446075582-3-8474/Cancer_show_034.JPG
   (0.7ms)  BEGIN
  SQL (0.9ms)  UPDATE "delayed_jobs" SET "attempts" = $1, "run_at" = $2, "locked_at" = $3, "locked_by" = $4, "updated_at" = $5 WHERE "delayed_jobs"."id" = $6  [["attempts", 5], ["run_at", "2015-10-28 23:56:45.336065"], ["locked_at", nil], ["locked_by", nil], ["updated_at", "2015-10-28 23:46:15.338022"], ["id", 22]]
   (1.7ms)  COMMIT
  Delayed::Backend::ActiveRecord::Job Load (1.9ms)  UPDATE "delayed_jobs" SET locked_at = '2015-10-28 23:46:15.344057', locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-10-28 23:46:15.343691' AND (locked_at IS NULL OR locked_at < '2015-10-28 19:46:15.343713') OR locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *
[Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] 3 jobs processed at 62.5742 j/s, 3 failed
2015-10-28T23:46:15+0000: [Worker(host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3)] 3 jobs processed at 62.5742 j/s, 3 failed
  Delayed::Backend::ActiveRecord::Job Load (1.4ms)  UPDATE "delayed_jobs" SET locked_at = '2015-10-28 23:46:15.347046', locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3' WHERE id IN (SELECT  "delayed_jobs"."id" FROM "delayed_jobs" WHERE ((run_at <= '2015-10-28 23:46:15.346718' AND (locked_at IS NULL OR locked_at < '2015-10-28 19:46:15.346737') OR locked_by = 'host:7db12935-5a60-41b4-892b-934f088b53d5 pid:3') AND failed_at IS NULL)  ORDER BY priority ASC, run_at ASC LIMIT 1 FOR UPDATE) RETURNING *

config/environments/production.rb

  config.action_mailer.perform_deliveries = true

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  include ::CarrierWave::Backgrounder::Delay

config/initializers/carrierwave_backgrounder.rb

CarrierWave::Backgrounder.configure do |c|
  c.backend :delayed_job, queue: :carrierwave
  # c.backend :resque, queue: :carrierwave
  # c.backend :sidekiq, queue: :carrierwave
  # c.backend :girl_friday, queue: :carrierwave
  # c.backend :sucker_punch, queue: :carrierwave
  # c.backend :qu, queue: :carrierwave
  # c.backend :qc
end

vehicle_image.rb

class VehicleImage < ActiveRecord::Base
  belongs_to :vehicle
  mount_uploader :image, ImageUploader
  process_in_background :image
  store_in_background :image

  def set_to_primary_and_save
    VehicleImage.where(vehicle: vehicle).update_all(primary: false)
    self.primary = true
    save
  end

end

Thanks for looking.

scope based on belongs_to fields

I have a message model which belongs to a user and a club.

The club model has deleted_at and suspended_at fields. I currently have a method that returns all the messages for a given message type e.g. messages.where(:type => 'application')

What I am looking to achieve is to adapt that method to show that message type only if deleted_at and suspended_at are nil on the associated club model.

Im not sure whether its best to adapt that method or have a default scope that doesnt return messages if the club deleted_at or suspended_at are not nil.

I am also unsure how to adapt the method or construct a scope based on the above logic. Can anyone point me in the right direction?

The app is using Rails 3.2.

Not getting custom category field value

On my App I have created two models Tutorial and Tutorial category and for tutorial i have created a string field for category ( in migration ) 'tutorialcategory'.

On tutorial add page I have added a selectbox field to select category and it is saving properly ( I hope ) as I can see the value after saving the tutorial in show page. but when I see full list using json render i can not see the value there.

Note : both models are separate and none of these contains reference field in migration

model code as follows

class Tutorialcategory < ActiveRecord::Base
    attr_accessible :title

    def to_param
        "#{id}-#{title}"
    end
end



class Tutorial < ActiveRecord::Base
  attr_accessible :body, :projectcategory, :rating, :title, :tutorialcategory, :videoid
end

How to write multiple queries in 'Order' clause with limits defined in rails

I have a model 'Product'. My requirement is to get all products in this fashion , top 20 products should be in order of created_at and remaining all should be in order of 'updated_at'. Right now my query is Product.order('created_at DESC,updated_at DESC'), but this gives me all products in order of 'created_at'. I want to put a limit clause inside 'order' clause. Any suggestions on how to achieve this?

'C: Carriage return character detected' for 'module WareHouse' in Rubocop

I am using rubocop in my application. I am facing a issue that is C: Carriage return character detected..

Here is my code.

module WareHouse
  class Stuff < ActiveRecord::Base
    # my code goes here
  end
end

Can anyone help me for this?

mercredi 28 octobre 2015

Rails create method to post object not working

I'm new to working with rails. I created a article posting form and when I click the post button it brings me to the articles page but it's not posting what I typed.

routes.rb:

get 'articles/new' => 'articles#new'
  post 'articles' => 'articles#create'

articles controller:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to '/articles'
    else
      render 'new'
    end
  end

  private

  def article_params
    params.required(:article).permit(:content)
  end
end

How to import parent/child objects in Elasticsearch

I'm using the gems elasticsearch-rails and elasticsearch-model in my Rails app. I'm using this integration test as a template for setting up my mappings and such before importing existing data, which has the same basic association between the parent and child models.

I know the integration test works because of the callbacks and that it sets the parent id in those callbacks.

I would like to import existing Questions and Answers. It doesn't seem like it's enough to just call Questions.import and Answers.import. I get the questions, but I don't get any answers in my Elasticsearch store. I'd like to know how to import the Answers objects with the appropriate parent mapping. Can anyone give me any hints?

[console in rails]. uninitialized constant Class

when i run a method in terminal of rails. first time, it working :

 Spree::Campaign.first
 Campaign Load (0.4ms)  SELECT  `campaigns`.* FROM `campaigns`   ORDER BY `campaigns`.`id` ASC LIMIT 1
 => #<Campaign id: 1, name: "campaign 1", user_id: 1, created_at: "2015-10-27 06:48:01", updated_at: "2015-10-29 04:22:03", description: nil, active: true>

but when i try run code above again

Spree::Campaign.first
NameError: uninitialized constant Spree::Campaign
from (irb):2
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/railties-4.1.6/lib/rails/commands/console.rb:90:in `start'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/railties-4.1.6/lib/rails/commands/console.rb:9:in `start'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:69:in `console'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/railties-4.1.6/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/railties-4.1.6/lib/rails/commands.rb:17:in `<top (required)>'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
from /home/kop/.rvm/gems/ruby-2.1.4@rails3213/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
from /home/kop/rails/donghoxteen/bin/rails:8:in `<top (required)>'
from /home/kop/.rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/kop/.rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from -e:1:in `<main>'

Why? and how to fix this error??

Reset password via API (doorkeeper) for devise

I am using devise and I want to reset password from native app (API) which is done throught doorkeeper ( oauth2 gem).

Actual requirement is to set password from native app using API. when 'reset password instruction' email will be sent to user, I want user to be able to reset password from API with three fields on APP side: password, confirm_password and reset_code (which should come from email also that should be simple 6 digit )

I found some solution to generate token for devise is like below:

 raw_token, hashed_token = Devise.token_generator.generate(User, :reset_password_token) 

But, I am not sure how should I re-set simple matchable and reset_password_token for API, which can be filled via custom form.

Please guide.

How to restrict two people log in with the same user credentials at any given time - Rails

I am researching on how to add protection to an existing rails app. The protection i need is to restrict two people log in with the same user credentials at any given time.

What would be the best approach around this?

I haven't seem to find any gem or something in particular.

Note that i am not using Devise but custom user authentication so please do not suggest anything related to devise.

Redmine add checkbox to existing plugin

i'm new with redmine so need some help

How to add new custom chekbox to existing plugin redmineCrm?

I want to add checkbox to form and new field to db

Also i want to configure it enable/disable through

http://ift.tt/1RBxkq1

How to do it?

How to load partial with using ajax

Indeed, in spite of setting ajax loading as 'remote=>true', it loads the url

'/noajax_en/v/yt/' + @movie.uid + '/refresh_part_after_comment'

Why it won't load ajax? it should load the url this below

'/en/v/yt/' + @movie.uid + '/refresh_part_after_comment'

Here's my code

view

<%= form_for(@comment, :url => {:controller => "comments", :action => "create" }, :remote => true) do |f| %>
    <%= f.text_field :body, id:"body_input" %>
    <%= f.hidden_field :elapsed_time, id: "elapsed_time" %>
    <%= f.hidden_field :video_id, value: params[:uid] %>
    <%= button_tag( :class => "btn btn-primary") do %>
        Post
    <% end %>                   
<% end %>

comments_controller.rb

def create
    .
    .
    .
    flash[:notice] = "posted"       

    if request.xhr?  # ajax request
        respond_to do |format|
            render '/en/v/yt/' + @movie.uid + '/refresh_part_after_comment'
        end
    else
            redirect_to '/noajax_en/v/yt/' + @movie.uid + '/refresh_part_after_comment'
    end
end

Show errors and stop form submission for nested forms

I have two models:

Order

OrderLineItem

I do not want to allow negative values to be entered into a nested form for order_line_items. That part is easy enough. The problem is when the form for orders gets submitted with a negative value the nested order_line_item form will also be submitted and fail in the order_line_item controller (as it should) silently and the order form will submit with the success flash message because in the order controller the order form was valid.

How do I get the submission to stop at the order_line_item failure show the flash error and not let the order submit?

order.rb

...
 accepts_nested_attributes_for :order_line_items
...

order_line_item.rb

...
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
...

orders_controller.rb

  def approve
    authorize!(:edit, :order)

    if @order_editable
      #do stuff
      flash[:notice] = "success"
    end
    redirect_to root_url
  end

order_line_items_controller

  def update
    if order_line_item_quantity >= 0
      #do stuff
    else
      flash[:error] = 'Error: Order line item cannot be a negative value'
      respond_with  @oli, error: flash[:error]
    end
  end

Multi-thread bug in rake task

I use Rails 3.2.22 and the gem Parallel. And I think I'm gonna be crazy because of class loading.

I use DelayedJob background job on Heroku and randomly some of my class is not defined and I have this kind of error NameError: uninitialized constant RequestAvailabilityForRoutes. So the first thing I've checked is to know if my class was well defined. So I've tried with no multi-thread, it seems working, but I want to use multi-thread..

Next, I've tried to change my autoload paths and follow this tutorial... Of course, no effect appeared...

And finally I find this issue http://ift.tt/1ka75w6. But I don't understand how to not fallback in non-thread-safe autoloading ..

My configuration in production is :

config.threadsafe!
config.dependency_loading = true if $rails_rake_task

What I'm doing wrong ? Is the gem I use ? There is a workaround I didn't know ?

Please help me.

I18n in Rails for filter

I have a problem I am unable to solve with internationalization in Rails. I am completely newbie in Rails.

I have a collection of categories defined in room.rb:

  CATEGORY_COLLECTION =  {
                  I18n.t('meeting_rooms') => "sala-de-reuniones",
                  "Aula de formación" => "aula-de-formacion",
                  "Sala para entrevistas" => "sala-para-entrevistas",
                  "Espacio para Eventos de Empresa" => "corporate-events",
                  "Showroom" => "showroom",
                  "Despacho" => "office",
                  "Sala multiusos" => "sala-multiusos",
                  "Puesto de Coworking" => "puesto-de-trabajo",
                  "Sala para conferencias" => "sala-para-conferencias",
                  "Sala de terapias" =>"sala-de-terapias",
                  "Otras salas" => "otras-salas",
                  "Espacio para rodaje" => "espacio-para-rodaje",
                  "Multiespacio" => "multiespacio",
                  "Fiesta de Navidad" => "christmas-events",
                  "Presentación de producto" => "product-presentation",
                  "Pop-up Stores" => "pop-up-stores",
                  "Show cooking" => "kitchen-studio",
                  "Shooting" => "shooting",
                  "Teatro" => "theater",
                  "Baile" => "dance-practice",
                  "Yoga" => "yoga",
                  "Performance" => "performance",
                  "Sala para fiestas particulares" => "sala-para-eventos"

As you can see, I have put the internationalization in the model, but when I want a dropdown with this, no internationalization.

Helper:

def categories
  @categories = Room::CATEGORY_COLLECTION
  @category_selected = Room::FILTER_CATEGORY_COLLECTION
end

Dropdown:

<%= f.select :categories_name_in, options_for_select(@categories, @category_selected), { include_blank: t('all_categories') }, { class: 'selectbox' } %>

The dropdown always appears in Spanish...

Thanks!

What is Layout_by_resource?

It is used in mostly all rails app but I couldn't find its meaning. I need to understand this code:

class ApplicationController < ActionController::Base
  layout :layout_by_resource

  protected

  def layout_by_resource
    if devise_controller?
      "layout_name_for_devise"
    else
      "application"
    end
  end
end

And this:

Rails.application.config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc { |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end

Undefined method `remember_me' in nested form for

I'm following Michael Hartl's tutorial but I'm getting this error when I run the bundle exec rake test:

1) Error:
UsersControllerTest#test_should_get_new:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x000000058544b8>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/controllers/users_controller_test.rb:6:in `block in <class:UsersControllerTest>'


  2) Error:
UsersSignupTest#test_invalid_signup_information:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x00000006acef08>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/integration/users_signup_test.rb:6:in `block in <class:UsersSignupTest>'


  3) Error:
UsersSignupTest#test_valid_signup_information:
ActionView::Template::Error: undefined method `remember_me' for #<User:0x000000074f6ff8>
    app/views/users/new.html.erb:25:in `block (2 levels) in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:24:in `block in _app_views_users_new_html_erb__1810619291483938060_46219160'
    app/views/users/new.html.erb:6:in `_app_views_users_new_html_erb__1810619291483938060_46219160'
    test/integration/users_signup_test.rb:17:in `block in <class:UsersSignupTest>'

This is the new.html.erb file:

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

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

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

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

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

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.label :remember_me, class: "checkbox inline" do %>
        <%= f.check_box :remember_me %>
        <span>Remember me on this computer</span>
      <% end %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

^Just like listing 8.47 in the rails tutorial http://ift.tt/1x2gdUr

It seems rails thinks :remember_me is a method, but why??? Why is :remember_me thought to be a method when all the other labels aren't??? I don't fkcing get it.

Background: I've went through half a ruby tutorial and entered this rails tutorial. i have very basic html and css abilities. Never touched ruby before. And I don't really understand half of the concepts in this chapter. I mostly just followed the instructions. So please, explain in noob terms :)

How to use ransack search to search association

i want to search products which are belonging to categories (saree, salwar).

i have the controller like this

class SearchController < ApplicationController def index q = params[:q] @key = q @products = Product.ransack(name_or_description_or_sku_or_category_id_in_cont: q).result(distinct: true).page(params[:page]).per(6) end end here it is selecting name description and sku , but categoty is not searching. hoe to do it in ransack?

my model is like this

product.rb belongs_to :category

category.rb has_many :products

in my product table fields include(name,description,image,category_id,sku)

please give a solution for this

Ruby On Rails : How to Put Space Inside tag in Rails With Multiple Variable Values To Render

I have a form which display the Full name of the customer in read only mode which look like bellow enter image description here

What I require is to have a white space in between First name, Middle name and Last name. I tried many times with different code but it failed, I am giving bellow my code, what to do ?

<div class="form-group">
          <label class="col-md-4 control-label" for="textinput">Customer Name :</label>  
          <div class="col-md-4">
          <b><input id="textinput" name="textinput" type="text" placeholder="placeholder" class="form-control input-md" value = <%= @lastcustomer.firstname%><%= @lastcustomer.middlename %><%= @lastcustomer.lastname %>  readonly> </b>
   </div>
</div>

mardi 27 octobre 2015

Preview emails in rails with text and html

In our Rails 3.2 app we have the following set up to preview emails:

examples_controller

def registration
    mail = EventMailer.registration(registration: EventRegistration.last, cache_email: false)
    return render_mail(mail)
  end

event_mailer.rb

def registration(options = {})
    @registration = options[:registration]
    @event = Event.find(@registration.event_id)
    @subject = options[:subject] || 'Your Learn Registration'

    return_email = mail(to: @registration.email, subject: @subject)

    # the email if we got it
    return_email
  end

We just added a text version of the emails, so now in app/views/event_mailer we have registration.html.erb and registration.text.erb. Before adding the text version of the email users could browse to /webmail/examples/registration and view the html version of the email. After adding the text email, that is broken.

Ideas on how to fix this? I tried setting multipart to false in the examples controller, but that did not work.

Also, here is the render_mail method...

def render_mail(mail)
    # send it through the inline style processing
    inlined_content = InlineStyle.process(mail.body.to_s,ignore_linked_stylesheets: true)
    render(:text => inlined_content, :layout => false)
  end

Searchkick error: Faraday::ConnectionFailed in PostsController#search

I am trying to add Searchkick gem in my app with Ruby on Rails but when i type a word in my search box i get this error in my app. I have installed elasticsearch and the latest version of java as required but still the error is the same. This is the error i am getting :

Faraday::ConnectionFailed in PostsController#search

Connection refused - connect(2) for "localhost" port 9200

Here's my code:

The Terminal shows that elastic search is installed:

Terminal

Warning: elasticsearch-1.7.3 already installed

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]


def search
  if params[:search].present?
    @posts = Post.search(params[:search])
  else
    @posts = Post.all
  end
end
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

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

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

  # GET /posts/1/edit
  def edit
  end

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

    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 @post, 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 posts_url, 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(:name)
    end
end

model/post.rb

class Post < ActiveRecord::Base
  searchkick
end

views/post/index.html.erb

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

<%= form_tag search_posts_path, method: :get, class: "navbar-form navbar-right", role: "search" do %>
        <p>
          <%= text_field_tag :search, params[:search], class: "form-control" %>
          <%= submit_tag "Search", name: nil, class: "btn btn-default" %>
        </p>
      <% end %>

<h1>Listing Posts</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.name %></td>
        <td><%= link_to 'Show', post %></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>

<br>

<%= link_to 'New Post', new_post_path %>

views/search.html.erb

<table>
  <thead>
    <tr>
      <th>Search Result</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.name %></td>
        <td><%= link_to 'Show', post %></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>

config/routes.rb

Rails.application.routes.draw do
  resources :posts do
  collection do
    get 'search'
  end
end
end

This is the screen i am getting with the error shown :

enter image description here

rails which is best place to save static html files

I have to save some html files and wanted to load them for some requirement. Currently i am placing that files in public folder. Also, i don't want to save it outside (amazon s3 etc) the rails application for some good reason. Please let me know which is idea way to do such functionality in Rails. I am using Rails 3.2.21

How to reload current page when destroy a micropost with AJAX in RAILS

guys! I'm start to learn RAILS. I have a list of micropost using pagination. And when I destroy a micropost, it go to first page. But I want when I destroy a micropost, it will reload a current page.

This is my code:

static_pages_controller.rb

def home
    return unless logged_in?
    @micropost  = current_user.microposts.build
    @feed_items = current_user.feed.paginate(page: params[:page])
end

microposts_controller.rb

def destroy
    @micropost.destroy
    @feed_items = current_user.feed.paginate(page: params[:page])
    respond_to do |format|
      format.html { redirect_to request.referrer || root_url }
      format.js
    end
  end

destroy.js.erb

$("#microposts").html("<%= escape_javascript(render('shared/feed')) %>");

_microposts.html.erb

<% if current_user?(micropost.user) %>
      <%= link_to "Delete", micropost, remote: true,
                                       method: :delete,
                                       data: { confirm: "You sure?" } %>
    <% end %>

_micropost.html.erb

<ol class="microposts" id="microposts_profile">
  <%= render @microposts %>
</ol>
<%= will_paginate @microposts %>

Do you have any idea to handle this problem?

How can I disable Authorization header cache in Ruby On Rails API?

I have developed a stateless RESTful API in Ruby On Rails. The way it works is that when you log in you receive a token, that you then use as an Authorization header to make requests.

There are two different roles available in the API: an Admin role and a Client role.

What I have done is add some role constraints to the routes so I can have the same endpoint pointing to different methods in the controller based on the specific role, like so (from config/routes.rb):

get '/courses', to: 'courses#admin_index', constraints: admin_constraints get '/courses', to: 'courses#client_index', constraints: client_constraints.

The constraints are implemented like this:

admin_constraints = RoleRouteConstraint.new(User::ROLES[:admin]) client_constraints = RoleRouteConstraint.new(User::ROLES[:client])

Where the RoleRouteConstraint retrieves the user that the Authorization header token belongs to, checks it's role and returns true if the role matches the constructor parameter.

The problem is that when I switch roles, Rails somehow caches my Authorization header from the previous role. Meaning that after I log in in the admin panel (as an admin), interact with the interface, and then go into the client interface, perform some actions, the API will keep my role as a client. If I then try to perform admin-specific actions, like so:

put '/courses/:id', to: 'courses#update', constraints: admin_constraints

I will not be able, since the API thinks I'm still logged in as a client. The thing is that it will work if I restart my rails server. Locally I'm using POW and in staging/production I'm using apache2. So if I perform a Rails restart and repeat the request as an admin, then it will work.

Anyone have any ideas please?

MySQL2: Lost connection to MySQL server during query

I am getting the following error when i am trying to use union:

ActionView::Template::Error (Mysql2::Error: Lost connection to MySQL server during query: SELECT  `apps`.* FROM `apps`  WHERE `verve_apps`.`status` IN (1, 2) AND (apps.id IN (SELECT apps.id FROM `apps`  WHERE `apps`.`status` IN (1, 2) AND (app_name LIKE '%b%') UNION SELECT apps.id FROM `verve_apps` INNER JOIN taggings ON taggings.taggable_id = apps.id                   INNER JOIN tags ON tags.id = taggings.tag_id AND taggings.taggable_type = 'App' WHERE `apps`.`status` IN (1, 2) AND (tags.name = 'b') ORDER BY id ASC)) ORDER BY app_name asc LIMIT 10 OFFSET 0)

app.rb

class App < ActiveRecord::Base

  include ActiveRecord::UnionScope

  acts_as_taggable
  attr_accessor: :user_name, :age, :country, tag_list
  scope :tagged_with, lambda { |tag|
    {
      :joins => "INNER JOIN taggings ON taggings.taggable_id = user.id\
               INNER JOIN tags ON tags.id = taggings.tag_id AND taggings.taggable_type = 'App'",
      :conditions => ["tags.name = ?", tag],
      :order => 'id ASC'
    }
  }
  def self.search(search)
    if search
      union_scope(where('name LIKE ?', "%#{search}%") ,tagged_with(search))
    else
      scoped
    end
  end
end

user_controller.rb

class UserController < ActionController::Base
  def index
    @users = User.search(params[:search]).paginate(:per_page => per_page, :page => params[:page])
  end

database.yml

pipe_local_development: &pipe_local_development
  adapter: mysql2
  encoding: utf8
  reconnect: true
  database: app_development
  pool: 5
  username: root
  password:

I am able to run this method from console without problems.

Problems with rails on Windows

I have installed rails from railsinstaller.org and i tried to run a

Rails new myrubyblog

and after the gems were created it told me

Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=SSLv3 read sever certificate B: certificate Verify failed (http://ift.tt/1OVdoPP)

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

After that occured i then ran:

gem install i18n -v '0.7.0' 

Then i ran

Rails new my

and the same thing occurred but instead it told me to run:

gem install json -v '1.8.3' 

I don't know what else to do now could someone help me.

Rails - Active Record Join across 3 Tables

somewhat new to Rails, so I'd appreciate any help you guys could offer.

Anyway, I have three models - Vote, Lunch, and Provider, and I'm looking to write a single Active Record call to pull:

  • All the data in the Vote table
  • The Lunch date in the Lunch table
  • The Provider name in the Provider table

The Vote model includes a lunch_id, the Lunch model includes a lunch_id (just called id) and the provider_id. The Provider model has a provider_id (just called an id.) In the Rails console, I can write:

v = Vote.joins(:lunch).select("lunches.date,votes.*").where(lunch_id: 1)

and that outputs all the data in the Vote model, plus the associated date from the Lunch model. Where I'm stuck is that I don't know how to "nest" this to then join to the Provider model.

I'm thinking this may have something to do with "has_many_through", but even after reading the documentation, I'm not sure how it would be implemented. Any thoughts here would be greatly appreciated!

why there are two ssl_certs folders in Centos

/usr/local/lib/ruby/2.1.0/rubygems/ssl_certs

/usr/local/lib/ruby/site_ruby/2.1.0/rubygems/ssl_certs

The contents are different as well.

The first one has the following .pem:

Class3PublicPrimaryCertificationAuthority.pem
DigiCertHighAssuranceEVRootCA.pem        
EntrustnetSecureServerCertificationAuthority.pem
GeoTrustGlobalCA.pem

The second one has the following .pem:

AddTrustExternalCARoot-2048.pem
AddTrustExternalCARoot.pem
Class3PublicPrimaryCertificationAuthority.pem
DigiCertHighAssuranceEVRootCA.pem
EntrustnetSecureServerCertificationAuthority.pem
GeoTrustGlobalCA.pem

Does using multiple ActionMailer classes increase memory overhead?

I'm currently using two Mailer classes in my Rails 3.2 app. One is AdminMailer, dedicated to sending emails to the internal team, and one is UserMailer to send emails to our registered users.

UserMailer is beginning to feel bloated, with 35 methods (i.e. 35 different emails) in it and counting. I could definitely take a subset of these emails that fit under a theme, and extract them out into a third Mailer class to make the code more manageable and readable.

My question is: Does it introduce more memory overhead on the app to need to instantiate more Mailer classes?

I tried searching for this on Google & Stack Overflow but didn't seem to find anything on the topic. Thanks!

How to render validation errors of form partial - Rails

So i am building a custom blog. So i have posts and comments.

I render comments through a partial on the show action of individual posts.

posts controller

 class Blog::PostsController < Blog::BaseController

  def show
    @post = Post.find_by_permalink(params[:id])
    @comment = Comment.new(:post => @post)
  end

end

comments controller

class Blog::CommentsController < Blog::BaseController

  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      flash[:success] = "Comment successfully created!"
      redirect_to blog_post_url(@comment.post)
    else
      flash[:warning] = "Something went wrong, try again. If problem persists please let our team know about it!"
      redirect_to :back
    end
  end

  private
      def comment_params
        params.require(:comment).permit(:body,:name,:email,:user_id,:post_id)
      end
end

and the show.html.erb

<div class="row post-container">
  <div class="large-offset-1 large-7 medium-12 columns post-content">
    <h1 class="post-title"> <%= link_to @post.title, blog_post_path(@post) %> </h1>
    <p class="published-date"><em>Published on <%= l @post.published_at, format: :date %></em></p>

    <div class="post-body">
      <%= @post.body.html_safe %>
      <%= render partial: "blog/comments/comment", post: @post %>
    </div>
  </div>
  <div class="large-4 columns sidebar">
    sidebar
  </div>
</div>

comments partial form

<%= form_for [:blog,@comment] do |f| %>
  <%= render 'blog/shared/error_messages', object: f.object %>

  <div class="field panel">
    <%= f.label :name %><br>
    <%= f.text_field :name,class: 'form-control' %>
  </div>

  <div class="field panel">
    <%= f.label :email %><br>
    <%= f.text_field :email,class: 'form-control' %>
  </div>

  <div class="field panel">
    <%= f.label :body, "Comment" %><br>
    <%= f.text_area :body,class: 'form-control' %>
  </div>

  <% if logged_in? %>
    <%= f.hidden_field :user_id, value: current_user.id %>
  <% end %>

  <%= f.hidden_field :post_id %>



  <div class="actions">
    <%= f.submit "Create comment", class:"btn btn-danger btn-block" %>
    <a class="btn btn-warning btn-block cancel">Cancel</a>
  </div>
<% end %>

so i tried to put validations on the comments model but it does not display them even though it correctly redirects back.

i know i have to use render instead of redirect but i do not know what to render and that is what i am trying to figure out since i do not have a render new action.

Cant seem to get my string to itterate in my view

Question I have a string that will have multiple values (person_ids and how many vacation days they have) I want to be able to use this data in my view. Any help would be greatly appreciated!

Here is my MyGroupAcc model

class MyGroupAcc < ActiveRecord::Base


belongs_to :entry



def self.all_people
  where(person_id: User.all.pluck(:person_id))
end

def self.active_people
  all_people.where(is_active: 'Y')
end

def self.active_vacation_data
  active_people.select(:person_id, :accum_accrued, :taken)
end

def total_v_hours
  accum_accrued.to_d - taken.to_d
end

def total_v_days
   total_v_hours / 8
end

And here is my entry controller where my view action will be

 def my_group
   peoples_vacation_information = MyGroupAcc.active_vacation_data.all
   peoples_vacation_information.map do |person|
      @p = "person #{person.person_id} has #{person.total_v_days} vacation days"
   end
   render :my_group
 end

And here is my_group view *(haml)

%table.table.table-bordered.trace-table
  %thead
    %tr.trace-table
      %th.ts.jp{:style => 'border: solid black;'} Person ID
      %th.ts.jp{:style => 'border: solid black;'} Total Vacation Days

      %tr.trace-table
      -@p.each do |r|
        %tr.trace-table
          %td.trace-table{:style => 'border: solid black;'}= r

In my view I get this error

  udefined method `each' for "person 22076 has 3.0 vacation days":String

but in my console it get this when running this code

 peoples_vacation_information = MyGroupAcc.active_vacation_data.all
 peoples_vacation_information.map do |person|
     @p = "person #{person.person_id} has #{person.total_v_days} vacation days"
 end

Which spits out this -> which is what I would like to see in my view.

    ["person 16016 has 7.0 vacation days", "person 16256 has 0.0 vacation days", "person 16256 has 18.5 vacation days", "person 17258 has 0.0 vacation days", "person 17258 has 5.0 vacation days", "person 17371 has 0.0 vacation days", "person 17371 has 20.0 vacation days", "person 19551 has 0.0 vacation days", "person 19551 has 26.5 vacation days", "person 20850 has 0.5 vacation days", "person 20850 has 14.0 vacation days", "person 21714 has 0.5 vacation days", "person 21714 has 1.0 vacation days", "person 22076 has 0.0 vacation days", "person 22076 has 3.0 vacation days"]

Undefined method `layout' for

I have method in my class Site::BaseController < ApplicationController

before_filter :check_layout

   def check_layout
    if @user.site_theme == 'hometastic'
      layout 'hometastic'
    else
      layout 'agent'
    end
  end

When i do only

layout 'agent'  

it works perfectly

but when i added before_filter i have got undefined method layout for

Rails 3.2.16

Any suggestions? error screen

How to exclude a controller (e.g. Notifycontroller ) from devise's session timeout

once define session expire timeout in devise.rb file it is available in entire rails application. But I want to exclude it from some specific controller say "Notifycontroller" which send notification in every couple of minute and my session expiration timeout is define after 30 minutes in devise.rb.

I want keep notifycontroller untouched from devise session expire timeout

rails: has_many_through queries with the wrong id

I'm using rails 3.0.20 and it seems that the has_many with :through relation is not querying with the correct id.

I have ElementType, which is a type of ProjectElement. Each ElementType has a number of ElementTypeParameters. The ProjectElement needs to know about the ElementTypeParameters.

class ProjectElement
  has_many :element_type_parameters, :through => :element_type
  ...
end

The element_type_id of this ProjectElement is 23, and it's id is 14902.

In the console...

>> ProjectElement.find(14902).element_type_parameters
  ElementTypeParameter Load (1.8ms)  SELECT "ELEMENT_TYPE_PARAMETERS".* FROM "ELEMENT_TYPE_PARAMETERS" 
  INNER JOIN "ELEMENT_TYPES" ON ("ELEMENT_TYPE_PARAMETERS"."ELEMENT_TYPE_ID" = "ELEMENT_TYPES"."ID") 
  WHERE (("ELEMENT_TYPES".id = 14902))

Is there any reason why it might be querying the element types table with the project element id instead of it's element_type_id column?

how to covert array object to hash in rails

i have a hash with array object :

{
  false=>[#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>], 
  true=>[#<Campaign id: 2, name: "campaign 2", active: true>]
} 

how to convert above hash to hash

{
  false=>[{id:1, name:"campaign 1"}, {id:3, name: "capaign 3"}, ....],
  true =>[{id:2, name:"campaign 2"}]
}

lundi 26 octobre 2015

While creating Change request and New Feature in Redmine, Target Version must be auto-filled and must be Read only

I have one new requirement in Redmine.

While creating CR/NF,Target Version must be auto-filled with a particular target version(Ex:Sprint 1) and It must also be read only.How can I do this requirement Please suggest me

Thank you

ActiveRecord::ReadOnlyRecord

I am getting ActiveRecord::ReadOnlyRecord error but unable to understand in which query.

So can you please help to find out which query that have ReadOnly Access.

When I am creating new record then unable to get error, I got error only when while I update the record.

Following is my logs.

Controller - Provider

  def update
    if @provider.update_attributes(params[:provider])
      flash[:notice] = "Saved changes to <strong>#{@provider.name}</strong>".html_safe
      redirect_to edit_clinic_provider_url(@provider.clinic, @provider) << "##{params[:anchor]}"
    else
      render :action => 'edit', :anchor => params[:anchor]
    end
  end

Backend Logs

Processing by ProvidersController#update as HTML
  Parameters: {"anchor"=>"contact", "utf8"=>"✓", "authenticity_token"=>"lWW6ifXtHDYPbFclDpS1QJ7cm+tMJn2zTa7J7cUNUDg=", "provider"=>{"clinic_id"=>"2", "signature_name"=>"Dimple Clinic", "provider_type_code"=>"Medical Doctor", "tax_uid"=>"111-11-1111", "upin_uid"=>"1111111111", "npi_uid"=>"1111111111", "contact_attributes"=>{"first_name"=>"DImple", "last_name"=>"Panchal", "phone1"=>"1111111111", "phone1_ext"=>"1", "fax1"=>"", "email1"=>"", "id"=>"10"}, "notes"=>"Test"}, "clinic_id"=>"2", "id"=>"2"}
  Account Load (0.3ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."deleted_at" IS NULL AND "accounts"."full_domain" = 'localhost' LIMIT 1
  User Load (0.8ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 3 AND ("users".account_id = 2) LIMIT 1
  Clinic Load (0.3ms)  SELECT "clinics".* FROM "clinics" WHERE "clinics"."deleted_at" IS NULL AND "clinics"."id" = 2 AND ("clinics".account_id = 2) LIMIT 1
  CACHE (0.0ms)  SELECT "clinics".* FROM "clinics" WHERE "clinics"."deleted_at" IS NULL AND "clinics"."id" = 2 AND ("clinics".account_id = 2) LIMIT 1
DEPRECATION WARNING: Base.named_scope has been deprecated, please use Base.scope instead. (called from included at (eval):1)
  Provider Load (2.2ms)  SELECT "providers"."id" AS t0_r0, "providers"."signature_name" AS t0_r1, "providers"."provider_type_code" AS t0_r2, "providers"."tax_uid" AS t0_r3, "providers"."upin_uid" AS t0_r4, "providers"."license" AS t0_r5, "providers"."notes" AS t0_r6, "providers"."nycomp_testify" AS t0_r7, "providers"."npi_uid" AS t0_r8, "providers"."contact_id" AS t0_r9, "providers"."address_id" AS t0_r10, "providers"."deleted_at" AS t0_r11, "providers"."created_at" AS t0_r12, "providers"."updated_at" AS t0_r13, "providers"."clinic_id" AS t0_r14, "contacts"."id" AS t1_r0, "contacts"."first_name" AS t1_r1, "contacts"."last_name" AS t1_r2, "contacts"."company_name" AS t1_r3, "contacts"."phone1" AS t1_r4, "contacts"."phone2" AS t1_r5, "contacts"."phone1_ext" AS t1_r6, "contacts"."phone2_ext" AS t1_r7, "contacts"."attention" AS t1_r8, "contacts"."notes" AS t1_r9, "contacts"."deleted_at" AS t1_r10, "contacts"."created_at" AS t1_r11, "contacts"."updated_at" AS t1_r12, "contacts"."title" AS t1_r13, "contacts"."phone3" AS t1_r14, "contacts"."phone3_ext" AS t1_r15, "contacts"."contactable_id" AS t1_r16, "contacts"."contactable_type" AS t1_r17, "contacts"."email1" AS t1_r18, "contacts"."email2" AS t1_r19, "contacts"."fax1" AS t1_r20, "contacts"."sex" AS t1_r21, "contacts"."occupation" AS t1_r22, "contacts"."middle_initial" AS t1_r23 FROM "providers" LEFT OUTER JOIN "contacts" ON "contacts"."id" = "providers"."contact_id" INNER JOIN "clinics" ON "providers".clinic_id = "clinics".id WHERE "providers"."deleted_at" IS NULL AND "providers"."id" = 2 AND (("clinics".account_id = 2)) ORDER BY contacts.last_name ASC, contacts.first_name ASC LIMIT 1
  Clinic Load (0.3ms)  SELECT "clinics".* FROM "clinics" WHERE "clinics"."deleted_at" IS NULL AND "clinics"."id" = 2 LIMIT 1
  Provider Load (0.1ms)  SELECT "providers"."id" FROM "providers" WHERE ("providers"."signature_name" = 'Dimple Clinic') AND ("providers".id <> 2) LIMIT 1
Completed   in 435ms

ActiveRecord::ReadOnlyRecord (ActiveRecord::ReadOnlyRecord):
  activerecord (3.0.5) lib/active_record/persistence.rb:245:in `create_or_update'
  activerecord (3.0.5) lib/active_record/callbacks.rb:277:in `block in create_or_update'
  activesupport (3.0.5) lib/active_support/callbacks.rb:428:in `_run_save_callbacks'
  activerecord (3.0.5) lib/active_record/callbacks.rb:277:in `create_or_update'
  activerecord (3.0.5) lib/active_record/persistence.rb:39:in `save'
  activerecord (3.0.5) lib/active_record/validations.rb:43:in `save'
  activerecord (3.0.5) lib/active_record/attribute_methods/dirty.rb:21:in `save'
  activerecord (3.0.5) lib/active_record/transactions.rb:240:in `block (2 levels) in save'
  activerecord (3.0.5) lib/active_record/transactions.rb:292:in `block in with_transaction_returning_status'
  activerecord (3.0.5) lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
  activerecord (3.0.5) lib/active_record/transactions.rb:207:in `transaction'
  activerecord (3.0.5) lib/active_record/transactions.rb:290:in `with_transaction_returning_status'
  activerecord (3.0.5) lib/active_record/transactions.rb:240:in `block in save'
  activerecord (3.0.5) lib/active_record/transactions.rb:251:in `rollback_active_record_state!'
  activerecord (3.0.5) lib/active_record/transactions.rb:239:in `save'
  activerecord (3.0.5) lib/active_record/persistence.rb:128:in `block in update_attributes'
  activerecord (3.0.5) lib/active_record/transactions.rb:292:in `block in with_transaction_returning_status'
  activerecord (3.0.5) lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
  activerecord (3.0.5) lib/active_record/transactions.rb:207:in `transaction'
  activerecord (3.0.5) lib/active_record/transactions.rb:290:in `with_transaction_returning_status'
  activerecord (3.0.5) lib/active_record/persistence.rb:126:in `update_attributes'
  app/controllers/providers_controller.rb:59:in `update'
  actionpack (3.0.5) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (3.0.5) lib/abstract_controller/base.rb:150:in `process_action'
  actionpack (3.0.5) lib/action_controller/metal/rendering.rb:11:in `process_action'
  actionpack (3.0.5) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
  activesupport (3.0.5) lib/active_support/callbacks.rb:480:in `_run__1006169370__process_action__404846983__callbacks'
  activesupport (3.0.5) lib/active_support/callbacks.rb:409:in `_run_process_action_callbacks'
  activesupport (3.0.5) lib/active_support/callbacks.rb:93:in `run_callbacks'
  actionpack (3.0.5) lib/abstract_controller/callbacks.rb:17:in `process_action'
  actionpack (3.0.5) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
  activesupport (3.0.5) lib/active_support/notifications.rb:52:in `block in instrument'
  activesupport (3.0.5) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  activesupport (3.0.5) lib/active_support/notifications.rb:52:in `instrument'
  actionpack (3.0.5) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
  actionpack (3.0.5) lib/action_controller/metal/rescue.rb:17:in `process_action'
  newrelic_rpm (3.14.0.305) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:30:in `block in process_action'
  newrelic_rpm (3.14.0.305) lib/new_relic/agent/instrumentation/controller_instrumentation.rb:362:in `perform_action_with_newrelic_trace'
  newrelic_rpm (3.14.0.305) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:29:in `process_action'
  actionpack (3.0.5) lib/abstract_controller/base.rb:119:in `process'
  actionpack (3.0.5) lib/abstract_controller/rendering.rb:41:in `process'
  actionpack (3.0.5) lib/action_controller/metal.rb:138:in `dispatch'
  actionpack (3.0.5) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
  actionpack (3.0.5) lib/action_controller/metal.rb:178:in `block in action'
  actionpack (3.0.5) lib/action_dispatch/routing/route_set.rb:62:in `call'
  actionpack (3.0.5) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
  actionpack (3.0.5) lib/action_dispatch/routing/route_set.rb:27:in `call'
  rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `block in call'
  rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `block in recognize'
  rack-mount (0.6.14) lib/rack/mount/code_generation.rb:117:in `optimized_each'
  rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
  rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
  actionpack (3.0.5) lib/action_dispatch/routing/route_set.rb:492:in `call'
  hoptoad_notifier (2.4.11) lib/hoptoad_notifier/rack.rb:27:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/head.rb:14:in `call'
  rack (1.2.8) lib/rack/methodoverride.rb:24:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/flash.rb:182:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/cookies.rb:302:in `call'
  activerecord (3.0.5) lib/active_record/query_cache.rb:32:in `block in call'
  activerecord (3.0.5) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
  activerecord (3.0.5) lib/active_record/query_cache.rb:12:in `cache'
  activerecord (3.0.5) lib/active_record/query_cache.rb:31:in `call'
  activerecord (3.0.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/callbacks.rb:46:in `block in call'
  activesupport (3.0.5) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
  actionpack (3.0.5) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
  rack (1.2.8) lib/rack/sendfile.rb:106:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
  railties (3.0.5) lib/rails/rack/logger.rb:13:in `call'
  rack (1.2.8) lib/rack/runtime.rb:17:in `call'
  activesupport (3.0.5) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.2.8) lib/rack/lock.rb:13:in `block in call'
  <internal:prelude>:10:in `synchronize'
  rack (1.2.8) lib/rack/lock.rb:13:in `call'
  newrelic_rpm (3.14.0.305) lib/new_relic/agent/instrumentation/middleware_tracing.rb:78:in `call'
  actionpack (3.0.5) lib/action_dispatch/middleware/static.rb:30:in `call'
  hoptoad_notifier (2.4.11) lib/hoptoad_notifier/user_informer.rb:12:in `call'
  railties (3.0.5) lib/rails/application.rb:168:in `call'
  railties (3.0.5) lib/rails/application.rb:77:in `method_missing'
  railties (3.0.5) lib/rails/rack/log_tailer.rb:14:in `call'
  rack (1.2.8) lib/rack/content_length.rb:13:in `call'
  rack (1.2.8) lib/rack/handler/webrick.rb:52:in `service'
  /home/dipak/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /home/dipak/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /home/dipak/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'
Rendered /home/dipak/.rvm/gems/ruby-1.9.3-p448/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)
  Provider Load (36.7ms)  SELECT "providers"."id" AS t0_r0, "providers"."signature_name" AS t0_r1, "providers"."provider_type_code" AS t0_r2, "providers"."tax_uid" AS t0_r3, "providers"."upin_uid" AS t0_r4, "providers"."license" AS t0_r5, "providers"."notes" AS t0_r6, "providers"."nycomp_testify" AS t0_r7, "providers"."npi_uid" AS t0_r8, "providers"."contact_id" AS t0_r9, "providers"."address_id" AS t0_r10, "providers"."deleted_at" AS t0_r11, "providers"."created_at" AS t0_r12, "providers"."updated_at" AS t0_r13, "providers"."clinic_id" AS t0_r14, "contacts"."id" AS t1_r0, "contacts"."first_name" AS t1_r1, "contacts"."last_name" AS t1_r2, "contacts"."company_name" AS t1_r3, "contacts"."phone1" AS t1_r4, "contacts"."phone2" AS t1_r5, "contacts"."phone1_ext" AS t1_r6, "contacts"."phone2_ext" AS t1_r7, "contacts"."attention" AS t1_r8, "contacts"."notes" AS t1_r9, "contacts"."deleted_at" AS t1_r10, "contacts"."created_at" AS t1_r11, "contacts"."updated_at" AS t1_r12, "contacts"."title" AS t1_r13, "contacts"."phone3" AS t1_r14, "contacts"."phone3_ext" AS t1_r15, "contacts"."contactable_id" AS t1_r16, "contacts"."contactable_type" AS t1_r17, "contacts"."email1" AS t1_r18, "contacts"."email2" AS t1_r19, "contacts"."fax1" AS t1_r20, "contacts"."sex" AS t1_r21, "contacts"."occupation" AS t1_r22, "contacts"."middle_initial" AS t1_r23 FROM "providers" LEFT OUTER JOIN "contacts" ON "contacts"."id" = "providers"."contact_id" INNER JOIN "clinics" ON "providers".clinic_id = "clinics".id WHERE "providers"."deleted_at" IS NULL AND (("clinics".account_id = 2)) ORDER BY contacts.last_name ASC, contacts.first_name ASC
Rendered /home/dipak/.rvm/gems/ruby-1.9.3-p448/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (47.5ms)
Rendered /home/dipak/.rvm/gems/ruby-1.9.3-p448/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (52.2ms)

How to give two different templates for two models using Ruby on Rails Devise library

I am fairly new to Ruby on Rails, and have a problem working with the devise library. I have two models with the devise library, and they need to have different registration fields.

Currently the default template lives in the folder app/app/views/devise/registrations/.

but potentially I would like to have something like app/app/views/devise/registrations/model1/registration_template.rb, app/app/views/devise/registrations/model2/registration_template.rb

Right now I am not sure where this is handled. They don't even have to live in separate folders as long as I can use two different templates for the two models and have the app be directed to the correct templates for each model.

Is `validates_presence_of` deprecated (as of Rails 3)?

According the the Rails 3 release notes, validate_presence_of is deprecated.

However, I can see no mention of this in the documentation (for v4.0.2).

Was this an error in the release notes/did it get re-precated/is the documentation wrong?

Why this won't load partial when using ajax loading?

Why this won't load partial?(chat comment DOM) But it loads the url /comments instead.

How can I load only partial? What am I missing here?

routes.rb

.
.
.
resources :comments
get ":lang/v/:site/:uid/refresh_part_after_comment" => 'movies#refresh_part_after_comment'
get ':lang/v/:site/:uid' => 'movies#show', :via => :get, :as => :watch_v
resources :movies
.
.
.

views/movies/show.html.erb (input form here!)

.
.
.
<div id="chat_comment">
    <%= render 'movies/comment' %>
</div>

<form action="/comments" method="post" data-remote="true" >
    <input type="text" name="body" size="50" id="body_input"/>
    <input type="hidden" name="elapsed_time" id="elapsed_time">
    <input type="hidden" name="video_id" value="<%= params[:uid] %>">
    <button type="submit" >Submit</button>
</form>
.
.
.

comments_controllr.rb

class CommentsController < ApplicationController
    def create

        if @user = User.find_by_twitter_id(session[:id])
        else
            @user = User.new
            @user.twitter_id = session[:id]
            @user.save
        end

        if @movie = Movie.find_by_uid(params[:video_id])

        else
            @movie = Movie.new
            @movie.uid = params[:video_id]
            @movie.save
        end

        @comment = Comment.build_from(@movie, @user.id, params[:body]) 
        @comment.elapsed_time = params[:elapsed_time]
        @comment.save

        flash[:notice] = "posted"       

        respond_to do |format|      
            format.js do
                render 'en/v/yt/' + @movie.uid + '/refresh_part_after_comment'
            end
        end

    end
end

movies_controller.rb

class MoviesController < ApplicationController
    .
    .
    .
    def refresh_part_after_comment
        if @movie = Movie.find_by_uid(params[:uid]) 
            @comments = @movie.comment_threads.order("elapsed_time ASC")
        end

        respond_to do |format|
            format.js 
        end
    end

    def show
        if @movie = Movie.find_by_uid(params[:uid]) 
            @comments = @movie.comment_threads.order("elapsed_time ASC")
        end

        respond_to do |format|
            format.html # show.html.erb
            format.json { render json: @movie }
        end
    end
    .
    .
    .
end

views/movies/refresh_part_after_comment.js.erb

$('#chat_comment').html("<%= j(render(:partial => 'movies/comment')) %>");

views/movies/_comment.html.erb

<% @comments.each do |comment| %>
    <%= comment.elapsed_time %>_<%= comment.body %><br />
<% end %>

ruby adding date 2000-01-01 for column type 'time' in mysql

how to get only time without date ruby + sequel for type time in MYSQL? ruby adding extra date '2000-01-01' with time for column type 'time' in MySQL. if the time '00:01:01' then ruby giving '2000-01-01 00:01:01 +530' in response with sequel.

dimanche 25 octobre 2015

RAILS: is there something like "html_safe_if()" or how to make a string "html_safe" if only a allowed subset eg &nbrsp; is used

My situation is, that I want to allow some HTML special chars (and prob some simple tags like bold) as user input (and output again).

AFAIK, the only way is to escape the buffer, and then unescape the allowed things and make it html_safe.

Take this simple example:

out_string = "abcd&#191;efgh"

renders abcd&#191;efgh if not with marked as html_safe, but renders abcd¿efgh if used with outstring.html_safe, that's not surprising.

What I would like to have is a "opt out" variant of html_safe that looks like html_safe_if([191, 160, ...]) therefore I need to do that (or something alike)

@out_string= ERB::Util.html_escape(@out_string).gsub("&amp;#191;","&#191;").html_safe

Escape it on my own, replace what is allowed and "html_safe it". Sure I can put that as function into the String class and put a bit more brain into the gsub, but isn't there a better, a ready solution?

Rails gem controller

I'm learning how to build a rails gem (engine, to be more specific). I first read some existing open source code like Devise, but I can't understand the controllers inside. In Devise/app/controllers there is devise_controller.rb with module hierarchy

 class DeviseController < Devise.parent_controller.constantize

but in Devise/lib/devise/controllers/ there are also many controllers with module hierarchy

module Devise 
  module Controllers

what's the difference between these controllers(like which is called when I get "users/sign_up")? Can someone who has experience more than using Devise according to tutorial explain?

Rails - continuing to work on check_box_tag

Continuing my project on themoviedb api, here is now what I have. I added a method to pass the attributes of the query. My method is:

def tmdb_search
  params.require(:tmdb_ids).permit(:id, :title, :release_date)
end

I pass this to:

def create_from_tmdb(tmdb_search)
  tmdb_search = params[:tmdb_ids]
  @movie = Tmdb::Movie.find(tmdb_search)
end

I proceed then in adding the movie to my db:

def add_tmdb(create_from_tmdb)
   create_from_tmdb = (params[:tmdb_ids])
   @movie = Movie.new(create_from_tmdb)
   @movie.save
   redirect_to movies_path
end

When I trying adding it, I get the wrong number of arguments (0 for 1) for the line def add_tmdb(create_from_tmdb).

The overall goal is to pass the result of my TMDB movie query from the view via check_box_tag, then saving it to my db. Here is the associated view:

- @movie.each do |movie|
  %tr
   %td= movie.title 
   %td= movie.release_date
   %td= check_box_tag 'tmdb_ids[]', movie.id
  = submit_tag 'Add selected movie'
   = link_to 'Return to movie list', movies_path

Rails asset pipeline concatenates application.css and js in development but not in production

We currently use the assest pipeline on our production server to precompile individual CSS and JavaScript assets, but don't combine them into a single file e.g. we have the following config:

config.assets.precompile += %w( *.js *css fonts/*)

I'm able to precompile the CSS and JavaScript files into a single CSS and single JS file on the development system configured with production settings. However, when I try to precompile on the production server I get no errors, just empty application.js and application.css files.

I've done a lot of reading up (including here on SO) and trying different things, but nothing seems to come close to being relevent. I'd love to hear any pointers or suggestions so the production application.css and application.js include the concatenated file contents.

Thanks in advance

Here are the relevent snippets of development and production configuration:

app/assets/stylesheets/application.css.scss.erb

/* ...
*= require cssexample1
*= require cssexample2
*/

app/assets/javascripts/application.js

//= require jsexample1
//= require jsexample2

config/application.rb

if defined?(Bundler)
  # If you precompile assets before deploying to production, use this line
  Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  # Bundler.require(:default, :assets, Rails.env)
end


module StudySoup
  class Application < Rails::Application


    # Enable the asset pipeline
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'
  end
end

Development setup

This creates the compiled application.js and application.css exactly as expected

ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
'RUBY_VERSION' in irb: 1.9.3
rails: 3.2.1
rake: 10.4.2

config/environments/development.rb

config.assets.debug = false

config.serve_static_files = true
config.assets.compress = true
config.assets.compile = true
config.assets.digest = true
config.assets.precompile += %w( *.js *css fonts/*)

Compiled with:

rm -rf tmp/cache/*
RAILS_ENV=development bundle exec rake assets:clean assets:precompile

Results:

public/assets/manifest.yaml contains entries and public/assests/application.js and application.css (and cache-busting copies) now contain the concatenated files

Production setup

This creates an empty application.js and applciation.css :(

ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
'RUBY_VERSION' in irb: 2.1.2
rails version: 3.2.1
rake, version 10.4.2

config/environments/production.rb

config.serve_static_assets = true
config.assets.compress = true
config.assets.compile = true
config.assets.digest = true
config.assets.precompile += %w( *.js *css fonts/*)

Compiled with:

rm -rf tmp/cache/*
rake assets:clean assets:precompile

Results:

public/assets/manifest.yaml contains entries and public/assests/application.js and application.css (and cache-busting copies) exist BUT are empty (length 0)