Tuesday, September 13, 2016

Rails doesn't update nested attributes | Fixed issues

Rails doesn't update nested attributes | Fixed issues


Rails doesn't update nested attributes

Posted: 13 Sep 2016 07:42 AM PDT

I create an application, which is basically a character creator for an RPG with interactive and dynamic forms. I use Rails 5.0.0.1, and I cannot update my form properly. The base model updates well, but all nested don't.

So, I have

class Character < ApplicationRecord    has_many :attr4characters, autosave: true    accepts_nested_attributes_for :attr4characters, allow_destroy: true  end  

and

class Attr4character < ApplicationRecord    belongs_to :character  end  

which represent a character and a set of his attributes. Each record in Attr4character is a different attribute.

The Show view is simple:

...  <div class="field">    <%= f.label :description %>    <%= f.text_area :description %>  </div>    <div class="field">    <%= f.label :character_type %>    <%= f.select(:character_type, options_for_select(["Zhong Lung", "Shih", "Hsien", "Garou", "Technocrat"])) %>  </div>      <% f.object.attr4characters.each do |attr| %>      <%= f.fields_for attr do |attr_f| %>        <div class="field">            <%= attr_f.label "Field name" %>          <%= attr_f.text_field :field_name %>        </div>        <div class="field">            <%= attr_f.label "Field value" %>          <%= attr_f.text_field :field_value %>        </div>      <% end %>    <% end %>      <div class="actions">      <%= f.submit %>    </div>  ...  

And finally my characters_controller:

  def update      respond_to do |format|        if @character.update(character_params)          format.html { redirect_to @character, notice: 'Character was successfully updated.' }          format.json { render :show, status: :ok, location: @character }        else          format.html { render :edit }          format.json { render json: @character.errors, status:  :unprocessable_entity }        end      end    end      private      def set_character        @character = Character.find(params[:id])      end        def character_params        params.require(:character).permit(:id, :name, :player, :description, :character_type, attr4characters_attributes: [:id, :character_id, :field_name, :field_value])      end  

So, I have a form, which correctly display a character and all set of his attributes. When I update a character field (like :description), it is normally updated. When I update any nested field, Rails says that character is successfully updated and nothing changes! I searched with Google, and I found a lot of problems with nested attributes in Rails forms, but none of the recipes worked for me. I even encountered opinions that it is a bug in Rails 4, but I use 5th version...

Please, advice on the topic. Is it a bug really? Or am I doing something wrong? I'm new on Rails, so I don't exclude that possibility. :)

By the way, in the server's log I found that there is warning about attr4characters.

Processing by CharactersController#update as HTML    Parameters: {"utf8"=>"\u2713", "authenticity_token"=>"xeYyIRc13YiOk29v18rFM6Oh5OHRRuPpSKEQuIHE/U4uhANEF7TwMp8mb6hv6L7mUAm5MngAuyFayHcWV/Vvbw==", "character"=>{"name"=>"Ray", "player"=>"111", "description"=>"A Zhong Lung suicider", "character_type"=>"Hsien", "attr4character"=>{"field_name"=>"Gift1", "field_value"=>"Sense Wyrm"}}, "commit"=>"Update Character", "id"=>"3"}    Character Load (0.2ms)  SELECT  "characters".* FROM "characters" WHERE "characters"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]  Unpermitted parameter: attr4character     (0.1ms)  begin transaction    SQL (0.9ms)  UPDATE "characters" SET "character_type" = ?, "updated_at" = ? WHERE "characters"."id" = ?  [["character_type", "Hsien"], ["updated_at", 2016-09-13 14:39:10 UTC], ["id", 3]]     (24.3ms)  commit transaction  

But attr4characters are permitted in the characters_controller...

I wan to upload image using papeclip but getting an error unknown attribute 'image' for Pic

Posted: 13 Sep 2016 07:38 AM PDT

My pic_controller.rb

image attribute exits in User Model still getting an error

ActiveRecord::UnknownAttributeError in PicsController#create

class PicsController < ApplicationController before_action :find_pic ,only: [:show,:edit,:update,:destroy] def index @pics = Pic.all.order("created_at DESC") end def new @pic = current_user.pics.build end

def destroy   @pic.destroy    redirect_to root_path  end    def show  end    def edit    end    def update   if @pic.update(pics_params)     redirect_to @pic, notice: "Congratz Pic is Updated"   else    render 'edit'   end  end    def create   @pic =current_user.pics.build(pics_params)    if @pic.save      redirect_to @pic, notice: "Yes it was created"    else      render  'new'    end   end  private  def pics_params    params.require(:pic).permit(:title,:description,:image)   end   def find_pic    @pic = Pic.find(params[:id])   end  end  

How to use helper methods to access elements from options_from_collection_for_select

Posted: 13 Sep 2016 07:31 AM PDT

The docs state options_from_collection_for_select(collection, value_method, text_method, selected = nil) has to have elements that respond_to? the value_method and the text_method.

What if my collection is an array of hashes and I need to use some helper methods for value_method and text_method?

For example,

collection = [{                  model: "LaF"                  year: 2016,                  mileage: 1230               },               {                  model: "P1",                  year: 2015,                  mileage: 1311               },               {                  model: "918",                  year: 2015,                  mileage: 2448               }  

]

For example: I want to be able to use the I18n.interpolate("car.mileage",mileage: element[:mileage]), method on the model key of each element.

TL;DR: How to call hash key methods or other helper methods on options_from_collection_for_select elements?

ActiveRecord only saves submission for one id

Posted: 13 Sep 2016 07:40 AM PDT

I'm trying to implement permissions and roles in a rails application. I have a role model and a permission model with a has_and_belongs_to_many relationship.

Inside the role model i have a method with which i can add permissions to roles and it works but active record only saves the permission with the id = 1.

In the console it says that the permission is assigned but when i type Role.first.permissions it doesn't show anything. I really don't understand what i am doing wrong since i also have the user model linked to the permission model in the same way, since i want to also be able to override the roles permissions on each individual user and there it works for every permission. Maybe this double linkage between permissions, roles and users is causing the problem?

Here is my role.rb:

class Role < ActiveRecord::Base      has_and_belongs_to_many :permissions,                               join_table: 'roles_permissions',                              association_foreign_key: 'role_id'        has_many :users          def add_permission(perm_id)        self.permissions << Permission.find(perm_id)      end        def remove_all_permissions        self.permissions.each do |i|          i.delete(Permission.all)        end      end        def remove_permission(id)        self.permissions.delete(Permission.find(id))      end  end  

Here is my user.rb:

class User < ActiveRecord::Base    has_and_belongs_to_many :permissions,                            association_foreign_key: 'permission_id',                            join_table: 'users_permissions'      belongs_to :role            def add_permission(perm_id)      self.permissions << Permission.find(perm_id)    end      def remove_all_permissions      self.permissions.each do |i|        i.delete(Permission.all)      end    end      def remove_permission(id)      self.permissions.delete(Permission.find(id))    end  end  

And here is my permission.rb:

class Permission < ActiveRecord::Base      has_and_belongs_to_many :roles, join_table: 'roles_permissions'      has_and_belongs_to_many :users, join_table: 'users_permissions'  end  

Here is the console log for the first permission:

irb(main):008:0> Role.first.add_permission(1)    Role Load (0.6ms)  SELECT  "roles".* FROM "roles"  ORDER BY "roles"."id" ASC LIMIT 1    Permission Load (0.6ms)  SELECT  "permissions".* FROM "permissions" WHERE "permissions"."id" = $1 LIMIT 1  [["id", 1]]     (0.1ms)  BEGIN    SQL (0.2ms)  INSERT INTO "roles_permissions" ("role_id") VALUES ($1)  [["role_id", 1]]     (0.5ms)  COMMIT    Permission Load (0.3ms)  SELECT "permissions".* FROM "permissions" INNER JOIN "roles_permissions" ON "permissions"."id" = "roles_permissions"."role_id" WHERE "roles_permissions"."role_id" = $1  [["role_id", 1]]  => #<ActiveRecord::Associations::CollectionProxy [#<Permission id: 1, name: "do_everything", created_at: "2016-09-13 13:45:54", updated_at: "2016-09-13 13:45:54", description: "God permission", role_id: nil>]>  irb(main):009:0> reload!  Reloading...  => true  irb(main):010:0> Role.first.permissions    Role Load (0.2ms)  SELECT  "roles".* FROM "roles"  ORDER BY "roles"."id" ASC LIMIT 1    Permission Load (0.2ms)  SELECT "permissions".* FROM "permissions" INNER JOIN "roles_permissions" ON "permissions"."id" = "roles_permissions"."role_id" WHERE "roles_permissions"."role_id" = $1  [["role_id", 1]]  => #<ActiveRecord::Associations::CollectionProxy [#<Permission id: 1, name: "do_everything", created_at: "2016-09-13 13:45:54", updated_at: "2016-09-13 13:45:54", description: "God permission", role_id: nil>]  

Here is the log for another permission:

irb(main):018:0> Role.first.add_permission(10)    Role Load (0.6ms)  SELECT  "roles".* FROM "roles"  ORDER BY "roles"."id" ASC LIMIT 1    Permission Load (0.4ms)  SELECT  "permissions".* FROM "permissions" WHERE "permissions"."id" = $1 LIMIT 1  [["id", 10]]     (0.1ms)  BEGIN    SQL (0.1ms)  INSERT INTO "roles_permissions" ("role_id") VALUES ($1)  [["role_id", 10]]     (0.8ms)  COMMIT    Permission Load (0.2ms)  SELECT "permissions".* FROM "permissions" INNER JOIN "roles_permissions" ON "permissions"."id" = "roles_permissions"."role_id" WHERE "roles_permissions"."role_id" = $1  [["role_id", 1]]  => #<ActiveRecord::Associations::CollectionProxy [#<Permission id: 10, name: "view_projects", created_at: "2016-09-13 13:45:54", updated_at: "2016-09-13 13:45:54", description: "Ability to view projects", role_id: nil>]>  irb(main):019:0> Role.first.permissions    Role Load (1.3ms)  SELECT  "roles".* FROM "roles"  ORDER BY "roles"."id" ASC LIMIT 1    Permission Load (0.5ms)  SELECT "permissions".* FROM "permissions" INNER JOIN "roles_permissions" ON "permissions"."id" = "roles_permissions"."role_id" WHERE "roles_permissions"."role_id" = $1  [["role_id", 1]]  => #<ActiveRecord::Associations::CollectionProxy []>  

The asset pipeline is currently disabled in this application. xray-rails

Posted: 13 Sep 2016 07:25 AM PDT

I am getting the following error when I am adding xray-rails in my Gemfile

The asset pipeline is currently disabled in this application. Either convert your application to use the asset pipeline, or remove xray-rails from your Gemfile.

  1. ruby: ruby-2.2.4
  2. rails: 4.2.6

Gemfile

...  gem 'rails', '4.2.6'  ...  group :development do    gem 'xray-rails', '0.1.17'  end  ...  

This is the log

$ rails s  => Booting WEBrick  => Rails 4.2.6 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Exiting  /home/deepak/.rvm/gems/ruby-2.2.4/gems/xray-rails-0.1.17/lib/xray/engine.rb:101:in `ensure_asset_pipeline_enabled!': xray-rails requires the Rails asset pipeline. (RuntimeError)  The asset pipeline is currently disabled in this application.  Either convert your application to use the asset pipeline, or remove xray-rails from your Gemfile.    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/xray-rails-0.1.17/lib/xray/engine.rb:10:in `block in <class:Engine>'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `call'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'    from /home/deepak/.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!'    from /home/deepak/sample/blog/config/environment.rb:5:in `<top (required)>'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'    from /home/deepak/sample/blog/config.ru:3:in `block in <main>'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'    from /home/deepak/sample/blog/config.ru:in `new'    from /home/deepak/sample/blog/config.ru:in `<main>'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/server.rb:61:in `app'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/server.rb:139:in `log_to_stdout'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/server.rb:78:in `start'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:80:in `block in server'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'    from /home/deepak/.rvm/gems/ruby-2.2.4/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'    from bin/rails:4:in `require'    from bin/rails:4:in `<main>'  

Should one use seperated seed files or fixtures for database? (Rails)

Posted: 13 Sep 2016 07:18 AM PDT

Up until now i've been using seeds (rake db:seed) to populate database. And i've split them apart, meaning, first i have the essential seeds (that are required for app to properly work), then i have separate code, for "development" environment, that adds users, and any other models, for easy testing. In live environment they are not run..

it usually looks something like so:

#seeds.rb    # essential data  User.create(admin: true, ..) # admin user    # development data  unless Rails.env.production?    # fill models with data, for easy testing, like products, there settings, etc..    # note that, i sometimes use faker here, for emails, nicknames, etc..    # this part is for creating stuff, like appointments or activities by users, like "likes", "shares", "comments", etc..  end  

Is this a good approach, or should i use fixtures to add data (that is used in every environment, except production?

Note that i dont have tests.

Conversion error thrown, but only from rake task

Posted: 13 Sep 2016 07:13 AM PDT

I'm having great difficulty with a piece of Rails code in which I'm writing data to a file using csv. This block:

  CSV.open(filename, "w", :force_quotes => true, :write_headers => true) do |csv|      for values in data        csv << values.map{|v| v.try(:to_s).try(:encode, "iso-8859-1").try(:force_encoding, "utf-8") }      end    end  

throws the following error:

#<Encoding::UndefinedConversionError: "\xC2" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to ISO-8859-1>  

The data in values is coming from a database.

The offending values is:

["Adjustable; adjustment range: camber: \xC2\xB13.0\xC2\xB0"]  

What I can't figure out is, it's only choking when this program is run from a rake task. If I set up a console session with the same variables and run that block of code, that text is converted to:

["Adjustable; adjustment range: camber: ±3.0°"]  

and written to a file successfully.

What is different about this running through a rake task versus the console?

mongoid `group by` query

Posted: 13 Sep 2016 07:13 AM PDT

In my rails application, there are two mongoid models which have a one-to-many relationship. I'm able to pick a selection of milestone ids and find all the Steps that belong to each milestone, but I need to group these steps or only return the steps from the latest milestone Steps if there are multiple. Milestones are order by position and Duplicate steps have the same step_id

ids = Milestones.where({'position' => { '$lte' => position }}).pluck(:id)  @steps= Steps.any_of({milestone_id: {"$in" => ids}, order_by: { milestone_id: ids }})  

How can I minify and concatenate a dir full of JavaScript files?

Posted: 13 Sep 2016 07:03 AM PDT

I'm working on a legacy Ruby on Rails 4 codebase.

It contains in assets/javascripts well over 100 .js files.

In production mode, it isn't so bad because the Rails Asset Pipeline minifies them and concatenates them into one file.

But in development, page refreshes take an extremely long time.

I want to compile (minify and concatenate) only a specific subdir (recursively) of JavaScript files in development mode.

Is there some tool I can point at a dir and output one minified .js file?

Ideally, this would be something that could watch a dir and recompile on changes.

I suspect that maybe Browserify or Webpack might be able to do that, but it isn't obvious to me from the docs how it would work in practice.

Rails: How to display Font Awesome icons on PDF

Posted: 13 Sep 2016 06:38 AM PDT

I use Font Awesome icons in some view in my Rails app, such as <i class="fa fa-male fa-fw" aria-hidden="true"></i>.

Now I'd like to generate PDF file, so I am trying to use PDFKit.

The following error was displayed when I click the link for PDF.

/usr/local/rvm/gems/ruby-2.3.0/gems/wkhtmltopdf-0.1.2/bin/wkhtmltopdf_linux_386: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory  Completed 500 Internal Server Error in 1123ms (ActiveRecord: 4.0ms)  Completed 500 Internal Server Error in 1123ms (ActiveRecord: 4.0ms)    RuntimeError (command failed (exitstatus=0): /usr/local/rvm/gems/ruby-2.3.0/bin/wkhtmltopdf --encoding UTF-8 --page-size A4 --margin-top 0.25in --margin-right 1in --margin-bottom 0.25in --margin-left 1in - -):    app/controllers/schedules_controller.rb:42:in `block (2 levels) in show'    app/controllers/schedules_controller.rb:29:in `show'  

I assume it may cause Font Awesome icons are used because libfontconfig error is displayed.

schedules\show.html.erb

<% provide(:title, @schedule.title) %>  <%= render @schedules %>  

schedules\ _schedule.html.erb

...      <%= link_to "PDF", schedule_path(schedule.id, format: "pdf"), class: "btn btn-sm btn-default" %>  ...  

schedules_controller.rb

...  respond_to do |format|    format.html # show.html.erb    format.pdf do      html = render_to_string template: "schedules/show"        pdf = PDFKit.new(html, encoding: "UTF-8")        send_data pdf.to_pdf,        filename:    "#{@scheudles.id}.pdf",        type:        "application/pdf",        disposition: "inline"    end  end  ...  

Line 42 in app/controllers/schedules_controller.rb:42:in block (2 levels) in show' is send_data pdf.to_pdf in the controller.

It would be appreciated if you could give me how to solve this error or a simpler technique to generate PDF. (it's ok to try in a different way (not PDFkit))

Trying to add a custom folder to assets path

Posted: 13 Sep 2016 07:06 AM PDT

I'm trying to add a custome folder to the assets path:

module MyApp    class Application < Rails::Application      config.assets.paths << Rails.root.join("something....")      # ....      config.assets.paths << Rails.root.join("app", "my_folder1", "fonts")  

I've restarted my app and when go directly to http://localhost:3000/my_folder1/fonts/my_font1.ttf or http://localhost:3000/my_folder1/my_font1.ttf in a browser, I get the error 404. Why? How to fix it? Note, it's in the folder "my_folder1" on purpose.

Rails asset pipeline require from public folder?

Posted: 13 Sep 2016 07:15 AM PDT

Is this a good practice to require assets located under public folder? e.g. I have lots of javascript under public/mythirdparyjs folder and I want to make these javascript files available for only specific page, what will be the best way to do this?

Ruby on rails confirm on submit tag with condition

Posted: 13 Sep 2016 06:30 AM PDT

On my edit page I will need to make a confirm box pop up if you try to set the end date before the start date.

I have a submit button, but need to get a confirm box coming up when the button is pressed but only if you have moved the end date before the start date. If you have not moved the end date before the start date it will not pop up.

I have so far used

<%=submit_tag "#{@record.id ? _('Save') : _('Create')}", :class=>"btn primary med", data: {:confirm => "Are you sure?"} %>  

but that doesn't do anything at all.

Belongs to many association?

Posted: 13 Sep 2016 06:42 AM PDT

I guess this is a pretty conceptual question. I'm looking through the possible associations available through Rails, but cannot seem to wrap my head around how to build a "belongs_to_many" and "has_many" association.

Specifically, I want readers to have many books, and each book to belong to many readers.

The closest I can find is the "has_many_and_belongs_to" association, but based on all of the examples I found, it is not exactly accurate.

Likewise, according to the documentation, the "belongs to" and "has many" association is meant as a one to many.

Is there an association available that matches a belongs to many style or some sort of model structure I could use?

line height not affecting anything in my app

Posted: 13 Sep 2016 06:25 AM PDT

I have a form like below in my rails app

<p class='field'>      <div class = "form-group">        <div class = "col-sm-3 mobile-label" >         <%= form.label :loyalty%>         <%=image_tag "qun1.png" ,:style=>"width: 15px; display:inline-block", 'data-toggle'=>"modal", 'data-target'=>"#myModal1"  %>       </div>       <div class="col-sm-9">        <%= form.text_field :coupon_code, :class => 'form-control col-sm-9' %>       <%= button_tag "Apply", class: 'btn btn-lg btn-success primary payment-code col-sm-3 ',id: 'apcode' %>      </div>      </div>  </p>    <p class='fild>    <div class = "form-group">      <div class = "col-sm-3 mobile-label" >       <%= form.label :coupon_code %>      </div>     <div class="col-sm-9">       <%= form.text_field :coupon_code, :class => 'form-control col-sm-9 ' %>       <%= button_tag "Apply", class: 'btn btn-lg btn-success primary payment-code col-sm-3 ',id: 'apcode' %>       </div>   </div>  </p>  

The result which I am getting is, there are no gap between the label.textfield and button element in both the form groups.

When I am giving line-height:30px; to my label, It completely breaks. Anything less than that is not affecting anything.

Here's the somewhat similar fiddle

Please help.

How to prevent child record from being added to the parent when there is validation error

Posted: 13 Sep 2016 06:08 AM PDT

I am studying ruby on rails with a parent child model relationship. In the parent show page, I have a table that lists the child records for this parent and a form to add new child record. The problem is, when I hit the submit button, the table displays a new blank row. How can I prevent this?

Here is my controller code:

def create    @parent = Parent.find(params[:parent_id])        @parent.children.create(child_params)      if @parent.valid?      redirect_to parent_path(@parent)    else      render 'parents/show'    end  end  

I have tried creating the Child model first instead of adding to the parent directly but it seems counter intuitive and I ran into issues with the validation.

Get specific user from many to many associations

Posted: 13 Sep 2016 05:59 AM PDT

I have many to many association through UserTask table. I need to get user with type creator from task (task.creator). It should be like task.user_tasks.where(user_type: 0) but with rails associations. Is it possible?

Here is my User model

class User < ApplicationRecord    has_many :user_tasks, foreign_key: 'user_email', primary_key: 'email'    has_many :tasks, through: :user_tasks  end  

Here is my Task model

class Task < ApplicationRecord    has_many :user_tasks, dependent: :destroy    has_many :users, through: :user_tasks  end  

Here is my UserTask model

class UserTask < ApplicationRecord    belongs_to :user, foreign_key: 'user_email', primary_key: 'email'    belongs_to :task    enum user_type: [:creator, :allowed]  end  

How to ask for user first_name last_name and then show it [on hold]

Posted: 13 Sep 2016 05:50 AM PDT

Sorry for this basic questions! Can anybody help? How can I ask for user first name on the welcome page and then refer to that name on other pages?

rails redirecting with notice message

Posted: 13 Sep 2016 06:21 AM PDT

I am redirecting the user to a subdomain of the application based on the parameter

respond_to do |format|        format.html {  redirect_to home_url(subdomain: params[:company]), notice: "Couldn't able to process your request, please try after some time" }  end  

with a notice message, and the html page to which i am redirecting the user looks like

<% flash.each do |name, msg| %>      <%= content_tag :div, msg, class: "alerts alerts-info bodyLeftPadd" %>  <% end %>  

for displaying the flash message.

But the problem here is the notice message is not displayed.

Is the use of subdomain causing this problem, because if remove the subdomain and if i redirect to the url within the same subdomain i could see the flash message being displayed.

 respond_to do |format|            format.html {  redirect_to home_url, notice: "Couldn't able to process your request, please try after some time" }   end  

RoR: Update attribute in a model from a unrelated controller

Posted: 13 Sep 2016 06:01 AM PDT

I need to pass a value to attribute in a model from a different controller with no direct relation between them. In the below example I need to update farming_year in the Field Model from the Planting controller.

The Field model:

class Field < ApplicationRecord    has_many :crops    attr_accessor :farming_year      def getting_crops      @crops_list = Crop.select('crops.name').where(field_id: self.id, year: get_farming_year)    end    def get_farming_year      @farming_year    end    def farming_year(val)      @farming_year = val    end  end  

In the Planting controller:

def new    @field = Field.new    @field.farming_year = session[:working_year] # doesn't work    .  end  

if I replaced the val in the Field model to be (@farming_year = 2016); the code will work. so that means the controller couldn't update the farming_year.

Any ideas how to achieve that?

Managing Multiple Hierarchical Rails Models Interlinked to Multiple Levels

Posted: 13 Sep 2016 05:10 AM PDT

I am building a To Do application but with multiple levels of tasks and subtasks. I have been following Ruby on Rails Tutorial by Michael Hartl and almost everything I have learnt till now is from there.

My app has multiple hierarchy models. What I mean is that at the top is the User, a user can have multiple goals, each goal can have multiple tasks, and each task can have multiple subtasks.

Just to give you a more clear idea, I'll list down the hierarchy

  • User
  • Goals (multiple goals per user)
  • Tasks (multiple tasks per goal)
  • Subtasks (multiple subtasks per task)

Now, when I created the models, I included a dependency (has_many/belongs_to) between goals and users, but I also did the same for tasks and users and subtasks and users. The reason for this is that I wanted an 'id' column in all tables that corresponds to the user table so that I can list down all subtasks/tasks/goals of a user very easily.

Coming to the front end, I need forms that are capable of adding goals/tasks/subtasks.

The relation between users and goals is not problematic at all. The has_many/belongs_to relation allows me to user something like

 def create    @goal = current_user.goals.build(path_params)       if @goal.save       redirect_to current_user     else      .      .     end     end  

However, the problem arises when I have 3 levels of hierarchy. User, goals and tasks.

My question is that how exactly do I do this for the task controller?

I tried using something like

@task = current_user.goals.tasks.build(task_params)  

but that has the obvious flaw apart from probably being syntactically incorrect : there is no way to detect what particular goal this task is being assigned to.

What I can think of is that the front end form must contain a field (perhaps hidden) that contains the goal ID to which the task is being assigned. But not entirely sure is this is correct as well or how if a front end gimmick like that can actually help in case there are even more levels of hierarchy.

Please tell me where I am going wrong / whats a better way to do this.

I am only a beginner right now so I am very confused on how multiple level model hierarchies are managed.

Getting '400 Bad request' after setting omniauth + twitter + devise

Posted: 13 Sep 2016 05:07 AM PDT

Here's what I did: In the devise initializer

config.omniauth :twitter, ENV["TrVSTS1gN040ffpuZ61gp7NLO"], ENV["gkm4LE8NwWZO00Tmf4Jr8eYOX9KFkVC5ItkfFbqqyKGfqUuO25"]  

In the gemfile

gem 'omniauth-twitter'  gem 'omniauth'  

In the view

<%= link_to 'Sin in with Twitter', user_omniauth_authorize_path(:twitter) %>  

In the user.rb

devise :database_authenticatable, :registerable, :omniauthable,       :recoverable, :rememberable, :trackable, :validatable  

the error

OAuth::Unauthorized  400 Bad Request      raise OAuth::Unauthorized, response  

How to allow delayed function to be delayed in Rails test environment

Posted: 13 Sep 2016 04:43 AM PDT

I have a Rails model class with a function to be executed at a later time, which is managed by Delayed::Job. Here is the function (simplified):

def fn_with_dj_delay    puts "puts output here"    do_somethting_else    end  handle_asynchronously :fn_with_dj_delay, :run_at => Proc.new { 24.hours.from_now }, :queue => 'my_queue'  

When the function is called in my Rails test environment however, the delaying is being skipped. Is it possible for this to perform the same in both environments?

In rails c test the function fires immediately. Here is a slightly simplified and truncated console log:

2.3.1 :004 > x = MyClass.new  2.3.1 :005 > x.save!  2.3.1 :006 > x.fn_with_dj_delay  puts output here   => #<Delayed::Backend::ActiveRecord::Job id: nil, priority: 0, attempts: 0 # ...  2.3.1 :007 > Delayed::Job.last    Delayed::Backend::ActiveRecord::Job Load (0.3ms)  SELECT  `delayed_jobs`.*  # ...   => nil  

In rails c the function is automatically delayed as instructed. Again, a slightly simplified and truncated console log:

2.3.1 :004 > x = MyClass.new  2.3.1 :005 > x.save!  2.3.1 :006 > x.fn_with_dj_delay     (0.2ms)  BEGIN    SQL (0.4ms)  INSERT INTO `delayed_jobs` (`handler`, `run_at`, # ...     (0.5ms)  COMMIT   => true  2.3.1 :007 > Delayed::Job.last      Delayed::Backend::ActiveRecord::Job Load (2.2ms)  SELECT  `delayed_jobs`.* # ...   => #<Delayed::Backend::ActiveRecord::Job id: 1, priority: 0, attempts: 0 # ...  

The only clue I can see is the returned, uninstantiated Delayed::Backend::ActiveRecord::Job object in the test console when the function finishes. If there is something invalid about the object, I could understand this failure, though I would expect an error to be raised. Regardless, this is not at issue:

2.3.1 :004 > res = p.check_for_similar_web_data  puts output here   => #<Delayed::Backend::ActiveRecord::Job id: nil, priority: 0, attempts: 0 # ...  2.3.1 :005 > res.valid?   => true  2.3.1 :006 > res.save!     (0.1ms)  BEGIN    SQL (0.4ms)  INSERT INTO `delayed_jobs` (`handler`, `run_at` # ...     (0.5ms)  COMMIT   => true  

Tag input field not working with turbolinks

Posted: 13 Sep 2016 04:47 AM PDT

I'm trying to create a ruby on rails project, and as part of this project I'm using this jQuery plugin to manage tags input. However the tag field works on first refresh but not after any page loads, I'm pretty sure this is a problem with turbolinks not running the js again.

So I installed this gem, and changed:

  $(function() {      $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();    });  })(window.jQuery);  

to:

  $(document).ready(function() {      $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();    });  })(window.jQuery);  

in bootstrap-tagsinput.js.

However this is still giving me the same issues. Any help fixing this would be great.

Is it possible to change the path for assets on the fly?

Posted: 13 Sep 2016 04:43 AM PDT

Is it possible to change the path for assets on the fly in before_filter from "assets" to something like "my_assets"? How can I do that? In the documentation there's no information about it.

elasticsearch mongoid filter on has_many ids

Posted: 13 Sep 2016 05:19 AM PDT

I'm using ES 1.4, Rails 5, and Mongoid 6. I'm also the mongoid-elasticsearch gem, which I don't think is relevant, but including it in case I'm wrong.

I have a Case model. When I run this query, everything works great, here's the query:

GET _search  {     "query":{        "filtered":{           "query":{              "query_string":{                 "query":"behemoth"              }           }        }     }  }  

Here's a result, notice the organization_id:

hits": [          {             "_index": "cases",             "_type": "case",             "_id": "57d5e583a46100386987d7f4",             "_score": 0.13424811,             "_source": {                "basic info": {                   "first name": "Joe",                   "last name": "Smith",                   "narrative": "behemoth"                },                "organization_id": {                   "$oid": "57d4bc2fa461003841507f83"                },                "case_type_id": {                   "$oid": "57d4bc7aa461002854f88441"                }             }          }  

See how there's that "$oid" for organzation id? That's because in my as_indexed_json method for Case, I have:

["organization_id"] = self.case_type.organization.id  

I think that the filter doesn't work b/c Mongoid somehow adds that subkey $oid. So my next thought was, I'll just make it a string:

["organization_id"] = self.case_type.organization.id.to_s  

But that throws an error:

{"error":"MapperParsingException[object mapping for [case] tried to parse as object, but got EOF, has a concrete value been provided to it?]","status":400}  

Anyone have any idea how to A) either use a mongo id as a filter, or B) get ES the info it needs so it doesn't complain as above?

Thanks for any help, Kevin

Rails - how to pass quantity and amount using Stripe

Posted: 13 Sep 2016 04:25 AM PDT

I'm building an events app using Ruby on Rails and I'm using Stripe to handle all the payments. I can't seem to figure out how to allow a user to be able to book and pay for more than one space at a time. I've used some javascript code for adding the number of spaces required and for the amount to reflect this on the booking page view. So an event at £10 per person(space on an event), for four people will be £40. When I do a Stripe test payment it only shows one payment being taken ( e.g £10 rather than £40 as per the example above).

This is what I have in my bookings table -

schema.rb - bookings

create_table "bookings", force: :cascade do |t|      t.integer  "event_id"      t.integer  "user_id"      t.string   "stripe_token"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false      t.integer  "quantity"    end  

I've included quantity here but I'm thinking I may need a column for amount / total amount?

Here's my controller -

bookings_controller.rb

class BookingsController < ApplicationController        before_action :authenticate_user!        def new          # booking form          # I need to find the event that we're making a booking on          @event = Event.find(params[:event_id])          # and because the event "has_many :bookings"          @booking = @event.bookings.new(quantity: params[:quantity])          # which person is booking the event?          @booking.user = current_user          #@booking.quantity = @booking.quantity          #@total_amount = @booking.quantity.to_f * @event.price.to_f          end              def create          # actually process the booking          @event = Event.find(params[:event_id])          @booking = @event.bookings.new(booking_params)          @booking.user = current_user            Booking.transaction do                @event.reload              if @event.bookings.count > @event.number_of_spaces              flash[:warning] = "Sorry, this event is fully booked."              raise ActiveRecord::Rollback, "event is fully booked"              end           end                  if @booking.save                # CHARGE THE USER WHO'S BOOKED              # #{} == puts a variable into a string              Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",                  card: @booking.stripe_token, description: "Booking number #{@booking.id}", items: [{quantity: @booking.quantity}])                flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          else              flash[:error] = "Payment unsuccessful"              render "new"          end            if @event.is_free?                @booking.save!              flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          end      end          private        def booking_params          params.require(:booking).permit(:stripe_token, :quantity)      end        end  

Having read through the API details I think the crux of the issue lies with the items: quantity element in the Stripe controller code block but I don't think I've got this right. Also, if I do need to add a total_amount column then this should be added into my booking params?

This is the method I have in my model at the moment -

    def total_amount            @booking.quantity * @event.price        end  

I'm pretty sure this is basic MVC stuff but I'm getting something fundementally wrong. This is my view for the bookings page -

bookings.new.html.erb

<div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Confirm Your Booking</h2>          </div>                    <div class="calculate-total">                                <p>                                    Confirm number of spaces you wish to book here:                                      <input type="number" placeholder="1"  min="1" value="1" class="num-spaces">                                </p>                                  <p>                                      Total Amount                                      £<span class="total" data-unit-cost="<%= @event.price %>">0</span>                                  </p>                            </div>                            <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>                         <span class="payment-errors"></span>                    <div class="form-row">                      <label>                        <span>Card Number</span>                        <input type="text" size="20" data-stripe="number"/>                      </label>                  </div>                    <div class="form-row">                    <label>                    <span>CVC</span>                    <input type="text" size="4" data-stripe="cvc"/>                    </label>                  </div>                    <div class="form-row">                      <label>                          <span>Expiration (MM/YYYY)</span>                          <input type="text" size="2" data-stripe="exp-month"/>                      </label>                      <span> / </span>                      <input type="text" size="4" data-stripe="exp-year"/>                  </div>              </div>              <div class="panel-footer">                       <%= form.button :submit %>                  </div>     <% end %>  <% end %>          </div>    </div>  </div>      <script type="text/javascript">      $('.calculate-total input').on('keyup change', calculateBookingPrice);    function calculateBookingPrice() {    var unitCost = parseFloat($('.calculate-total .total').data('unit-cost')),        numSpaces = parseInt($('.calculate-total .num-spaces').val()),        total = (numSpaces * unitCost).toFixed(2);      if (isNaN(total)) {      total = 0;    }      $('.calculate-total span.total').text(total);  }      $(document).ready(calculateBookingPrice)    </script>        <script type="text/javascript" src="https://js.stripe.com/v2/"></script>    <script type="text/javascript">    Stripe.setPublishableKey('<%= STRIPE_PUBLIC_KEY %>');    var stripeResponseHandler = function(status, response) {      var $form = $('#new_booking');        if (response.error) {      // Show the errors on the form      $form.find('.payment-errors').text(response.error.message);      $form.find('input[type=submit]').prop('disabled', false);      } else {      // token contains id, last4, and card type      var token = response.id;      // Insert the token into the form so it gets submitted to the server      $form.append($('<input type="hidden" name="booking[stripe_token]"     />').val(token));      // and submit      $form.get(0).submit();      }    };      // jQuery(function($)  { - changed to the line below    $(document).on("ready page:load", function () {        $('#new_booking').submit(function(event) {        var $form = $(this);          // Disable the submit button to prevent repeated clicks        $form.find('input[type=submit]').prop('disabled', true);          Stripe.card.createToken($form, stripeResponseHandler);          // Prevent the form from submitting with the default action        return false;      });    });  </script>  

Encoding::InvalidByteSequenceError: "\xAB" on UTF-8 in Rails 5

Posted: 13 Sep 2016 04:45 AM PDT

Whenever I try to use a stylesheet_link_tag or javascript_include_tag in Rails 5 on Ruby 2.3.1, I get an Encoding::InvalidByteSequenceError: "\xAB" on UTF-8. This is despite all my CSS/JS files being in UTF-8 (I checked). Please help.

From application.html.erb:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => 'reload' %> is the line throwing an error.

Full stack trace at https://gist.github.com/mindseyeblind/dbeef97e70c034f4705f70ff5bc2ed9d

I have no idea about where I should place config.json file in rails

Posted: 13 Sep 2016 05:54 AM PDT

I'm using gem 'google_drive'. This gem provides functions to manipulate Google Drive Files. First of all, I have to create config.json as below

{    "client_id": "my-client-id",    "client_secret": "my-client-secret"  }  

And, Authenticate with

session = GoogleDrive::Session.from_config("path/to/config.json")  

Then, config.json will be rewritten as below

{    "client_id": "my-client-id",    "client_secret": "my-client-secret",    "scope": [      "https://www.googleapis.com/auth/drive",      "https://spreadsheets.google.com/feeds/"    ],    "refresh_token": "refresh-token"  }  

I don't wanna place config.json in the root of my application.


Where is the best place to put config.json?

I was thinking about putting it in config/config.json

This seems like a good place to me. But, on the other hand, I think the config directory should contain files that will not be changed while application is running, and config.json will be rewritten by GoogleDrive while application is running.

when i am trying to execute rails it says 'missing_extensions?'

Posted: 13 Sep 2016 04:34 AM PDT

C:\Sites>rails new the_blog        create        create  README.rdoc        create  Rakefile        create  config.ru        create  .gitignore        create  Gemfile        create  app        create  app/assets/javascripts/application.js        create  app/assets/stylesheets/application.css        create  app/controllers/application_controller.rb        create  app/helpers/application_helper.rb        create  app/views/layouts/application.html.erb        create  app/assets/images/.keep        create  app/mailers/.keep        create  app/models/.keep        create  app/controllers/concerns/.keep        create  app/models/concerns/.keep        create  bin        create  bin/bundle        create  bin/rails        create  bin/rake        create  bin/setup        create  config        create  config/routes.rb        create  config/application.rb        create  config/environment.rb        create  config/secrets.yml        create  config/environments        create  config/environments/development.rb        create  config/environments/production.rb        create  config/environments/test.rb        create  config/initializers        create  config/initializers/assets.rb        create  config/initializers/backtrace_silencers.rb        create  config/initializers/cookies_serializer.rb        create  config/initializers/filter_parameter_logging.rb        create  config/initializers/inflections.rb        create  config/initializers/mime_types.rb        create  config/initializers/session_store.rb        create  config/initializers/wrap_parameters.rb        create  config/locales        create  config/locales/en.yml        create  config/boot.rb        create  config/database.yml        create  db        create  db/seeds.rb        create  lib        create  lib/tasks        create  lib/tasks/.keep        create  lib/assets        create  lib/assets/.keep        create  log        create  log/.keep        create  public        create  public/404.html        create  public/422.html        create  public/500.html        create  public/favicon.ico        create  public/robots.txt        create  test/fixtures        create  test/fixtures/.keep        create  test/controllers        create  test/controllers/.keep        create  test/mailers        create  test/mailers/.keep        create  test/models        create  test/models/.keep        create  test/helpers        create  test/helpers/.keep        create  test/integration        create  test/integration/.keep        create  test/test_helper.rb        create  tmp/cache        create  tmp/cache/assets        create  vendor/assets/javascripts        create  vendor/assets/javascripts/.keep        create  vendor/assets/stylesheets        create  vendor/assets/stylesheets/.keep           run  bundle install  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  rubygems_ext.rb:23:in `source': uninitialized constant Gem::Source::Installed (N  ameError)          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/rubygems_ext.rb:65:in `extension_dir'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:1782:in `gem_build_complete_path'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:1996:in `missing_extensions?'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/basic_specifica  tion.rb:67:in `contains_requirable_file?'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `block in find_in_unresolved'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `each'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `find_all'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `find_in_unresolved'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:74:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/source.rb:228:i  n `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/rubygems_ext.rb:23:in `source'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/rubygems_ext.rb:65:in `extension_dir'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:1782:in `gem_build_complete_path'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:1996:in `missing_extensions?'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/basic_specifica  tion.rb:67:in `contains_requirable_file?'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `block in find_in_unresolved'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `each'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `find_all'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/specification.r  b:949:in `find_in_unresolved'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:74:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/rubygems_integration.rb:4:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler.rb:11:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:128:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:128:in `rescue in require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:39:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/generators/app_base.rb:330:in `bundle_command'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/generators/app_base.rb:346:in `run_bundle'          from (eval):1:in `run_bundle'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/command.rb:27:in `run'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/invocation.rb:126:in `invoke_command'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/invocation.rb:133:in `block in invoke_all'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/invocation.rb:133:in `each'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/invocation.rb:133:in `map'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/invocation.rb:133:in `invoke_all'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/group.rb:232:in `dispatch'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li  b/thor/base.rb:440:in `start'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/application.rb:17:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/cli.rb:14:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel  _require.rb:69:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/bin/rails:9:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/bin/rails:23:in `load'          from C:/RailsInstaller/Ruby2.2.0/bin/rails:23:in `<main>'    C:\Sites>ls  the_blog    C:\Sites>cd the_blog    C:\Sites\the_blog>rails server  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:94:in `rescue in block (2 levels) in require': There was an error whi  le trying to load the gem 'uglifier'. (Bundler::GemRequireError)  Gem Load Error is: Could not find a JavaScript runtime. See https://github.com/r  ails/execjs for a list of available runtimes.  Backtrace for gem load error is:  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/execjs-2.7.0/lib/execjs/run  times.rb:58:in `autodetect'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/execjs-2.7.0/lib/execjs.rb:  5:in `<module:ExecJS>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/execjs-2.7.0/lib/execjs.rb:  4:in `<top (required)>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/uglifier-3.0.2/lib/uglifier  .rb:5:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/uglifier-3.0.2/lib/uglifier  .rb:5:in `<top (required)>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:91:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:91:in `block (2 levels) in require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:86:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:86:in `block in require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:75:in `each'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler/  runtime.rb:75:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0/lib/bundler.  rb:106:in `require'  C:/Sites/the_blog/config/application.rb:7:in `<top (required)>'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands/commands_tasks.rb:78:in `require'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands/commands_tasks.rb:78:in `block in server'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands/commands_tasks.rb:75:in `tap'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands/commands_tasks.rb:75:in `server'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands/commands_tasks.rb:39:in `run_command!'  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/  commands.rb:17:in `<top (required)>'  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Bundler Error Backtrace:          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/runtime.rb:90:in `block (2 levels) in require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/runtime.rb:86:in `each'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/runtime.rb:86:in `block in require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/runtime.rb:75:in `each'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler/runtime.rb:75:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.0  /lib/bundler.rb:106:in `require'          from C:/Sites/the_blog/config/application.rb:7:in `<top (required)>'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/commands_tasks.rb:78:in `require'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/commands_tasks.rb:78:in `block in server'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/commands_tasks.rb:75:in `tap'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/commands_tasks.rb:75:in `server'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5  .1/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'    C:\Sites\the_blog>  

No comments:

Post a Comment