Monday, August 22, 2016

How to access a Service in a Rails Engine by using default Engine's namespace? | Fixed issues

How to access a Service in a Rails Engine by using default Engine's namespace? | Fixed issues


How to access a Service in a Rails Engine by using default Engine's namespace?

Posted: 22 Aug 2016 07:40 AM PDT

I have built a mountable Rails Engine (4.2.6) with the name System in folder lib/engines/system. Inside the app directory, I've created another one called Services and I've added a file system_manager_service.rb with a class SystemManagerService.

Now I want to create a new object of this class. I usually use engines by calling functions like (If there's a model called Service) System::Service.do_something. But in this case, I try to use System::SystemManagerService.new and what happens is that the first time I visit the page I get a message:

uninitialized constant System::SystemManagerService  

I've tried all combinations I've imagined, like including the class SystemManagerService inside module System like:

module System       class SystemManagerService      end  end  

and it works but the second time I load the page.

I've also tried to require_dependency but it failed because app/services is outside lib folder.

How can I achieve creating an object from a class living inside app/services folder in a Rails Engine ?

How to maintain 2 versions of Rails for a project moving to Rails 5?

Posted: 22 Aug 2016 07:38 AM PDT

My suite of Rails 4.2 apps and gems are currently being upgraded to Rails 5. Is there a way to maintain 2 seperate Gemfiles and Gemfiles - one for Rails 4.2 and another for Rails 5, and push this off to git, so multiple people can work on the apps in both Rails 4.2 and Rails 5?

How to limit concurrent user session in rails app that uses devise?

Posted: 22 Aug 2016 07:30 AM PDT

Limiting concurrent user sessions or login:

For a user I needs to apply limit while login. I want to allow a user user@gmail.com to be able to login from different 5 PCs or browsers only.

What I used:

I added two fields to users table called session_limit (to specify user login limits) and session_count( to store currently running sessions for that user).

I added one to session_count when user login and subtract one from session when user logout or timeout occurs. I checked session_count while logging in and logged out when it reaches session_limit. It worked fine at first.

What problem I faced:

When user closes browser without logout session_count remains not deducted and when user logins next time it says user_session limit reached. Even if there is none logged in.

Please Help.

Determine if using Rails console or server when using Spring

Posted: 22 Aug 2016 07:18 AM PDT

Is it possible to determine if you are in the context of a running Rails server or console in an initializer when Spring is used? I've seen similar questions that don't take Spring into account.

undefined method to each do Ruby on rails

Posted: 22 Aug 2016 07:39 AM PDT

I have two tables: Dimensions and Task. For each dimension have N task. so in Task Controller i have this:

def new    @dimensions =  Dimension.all    @dimensions.each do |dimension|      @task = Task.new    end  end   

and the view Task this

<h1>Tasks#new</h1>  <%= form_for(@task) do |task| %>    <div class='service'>      <li class="col-md-3">        <div class="thumbnail">          <div class="caption">            <h4><%= task.name %></h4>            <p><%= task.description %></p>          </div>          <span>          </span>        </div>      </li>    </div>  <% end %>  

but on the task view it shows me this error message

undefined method 'name'

undefined method 'descripcion'

Iterate 4 Arrays with Rails

Posted: 22 Aug 2016 07:33 AM PDT

I'm new to Rails and I'm trying to build a nice application and I'm struggling with arrays, I have 4 arrays that I want to iterate and they are not the same size

I want to generate sections in HTML using the first array what I did it

@sections = ['Section One','Section Two','Section Three','Section Four']  @itemsOne = ['item 1','item 2','item 3','item 4','item 5','item 6']  @itemsTwo = ['item 1','item 2','item 3','item 4','item 5','item 6']  

I was using

<%= @sections.zip(@itemsOne, @itemsTwo).each do |t1, t2, t3| %>  <%= t1 %>  <table>      <tbody>          <tr>              <td>                  <%= t2 %> | <%= t3 %>              </td>              <td>                  <%= t2 %> | <%= t3 %>              </td>              <td>                  <%= t2 %> | <%= t3 %>              </td>          </tr>      </tbody>  </table>  <% end %>  

I have a table that have a Section Title and cells that have two values

but what I get is the value of |t2| in each first cell of |t1| section

p.s. the itemsOne and itemsTwo arrays have more than 20 values.

paperclip obfuscation renaming

Posted: 22 Aug 2016 07:03 AM PDT

I am using the paperclip gem and wanted to use the obfuscation function to mask the images. I am currently getting the following error

ActionController::RoutingError (No route matches [GET] "/system/users/avatars/000/000/002/square/f65043316b604467fdc350dc64f23ccbf2d43fca.jpg"):  

I have set my code up as below

has_attached_file :avatar,    {        styles: { square: '200x200#' },        path: ":rails_root/public:url",        url: "/system/:class/:attachment/:id_partition/:style/:hash.:extension",        hash_secret: 'abfa04a42c94f58d17a509bccb2276d2f2e1718e23de5f0ff4bc93b4c922c2dbd23f81b31a7932fbf4424c95f14e055639d2376f8b3cb40ebf91ea4682197645'    }  

and the file which is being uploaded is renamed as

263b6c224069d97527fc799208b9d5c3d5a67c5d.jpg  

using `find_by` on a serialized hash causes `SerializationTypeMismatch: Attribute was supposed to be a Hash, but was a String`

Posted: 22 Aug 2016 06:51 AM PDT

I have a serialized hash in a model that I want to query for:

class MyModel < ActiveRecord::Base    serialize :data, Hash    # e.g. contains {"1" => "pass", "2" => "fail"}  end  

Looks fine in the database and can use the column via console with no issue. Data appears like so before typecast: "---\n'1': pass\n'2': fail\n"

I want to then query this column:

MyModel.find_by_data({"1" => "pass", "2" => "fail"})   # Gives an undefined table error    MyModel.where("data = ?", {"1" => "pass", "2" => "fail"}.to_yaml).first  # Works, so long as there is a result    MyModel.find_by_data({"1" => "pass", "2" => "fail"}.to_yaml)      # Gives ActiveRecord::SerializationTypeMismatch:   # Attribute was supposed to be a Hash, but was a String. -- "---\n'1': pass\n'2': fail\n"  

Would be grateful for any suggestions. Ruby 2.0, Rails 4.1

Model association on foreign key that is not integer

Posted: 22 Aug 2016 06:35 AM PDT

I'm building an API in rails, and I have 2 models : Vehicle which has_one: :document

class CreateVehicles < ActiveRecord::Migration     def change        create_table :vehicles do |t|            t.string :uuid, limit: 36, null: false, index: true            t.string :license_plate_id            t.integer :mileage            t.string :mileage_unit, default: 'km'            t.belongs_to :user, index: true              t.timestamps null: false          end      end  end  

VehicleDocument belongs_to: :Vehicle

class CreateVehicleDocuments < ActiveRecord::Migration     def change        create_table :vehicle_documents do |t|           t.string :uuid, limit: 36, null: false, index: true           t.integer :status, default: 0           t.attachment :file           t.belongs_to :vehicle, index: true           t.timestamps null: false        end        add_index :vehicle_documents, :status     end   end  

the problem is that I want to use a uuid for the vehicle id. I don't want to expose the real ID outside of my API. how must I do this ? Do I have to do this in the migration file ? model ? Should I not be doing this ? Thanks a lot

Update an attribute with value from loop

Posted: 22 Aug 2016 06:43 AM PDT

I'm building an app to store sport games, for this all users will be placed in seperated leagues. I've set up a many to many for this but when a user looks at the application he can only see all the info from it's current_league.

Now I'm trying to make a loop with all the leagues a user is in and the user should be able to click the league to change it's active league.

Routes

  resources :users do      member do        post :change_current_league        end    end  

UserController

def change_current_league      @user = current_user      @user.update(:current_league_id, params[:league_id])      redirect_to :back, :notice => "Successfully changed your active league"  end  

View

<% current_user.leagues.each do |l| %>      <%= link_to change_current_league_user_path(current_user, l), method: :post, class: 'btn btn-default btn-sm' do %>                            <%= l.id %><%= l.league_name %><br>  <% end %>          <% end %>  

What should I do to get this to work?

Sorry if its a bit of a noob question :P

EDIT:

def change_current_league      @user = current_user      @user.update_attribute(:current_league_id, 1)      redirect_to :back, :notice => "Successfully changed your active league"  end        resources :users do      member do        patch :change_current_league        end    end  

This is working but how do I get the correct league_id into the user controller?

EDIT2:

def change_current_league      @league = League.find(params[:league_id])        @user = current_user        @user.update_attribute(:current_league_id, @league)        redirect_to :back, :notice => "Successfully changed your active league"  end  

AWS Elastic Beanstalk, create environment failed.

Posted: 22 Aug 2016 05:50 AM PDT

I am using EB for the first time, attempting to upload a Ruby on Rails application from Github to AWS. I am following the step-by-step guide, but I continue running into an error:

$ eb create betz5-env  Creating application version archive "app-7f74-160822_083029".  Uploading betz/app-7f74-160822_083029.zip to S3. This may take a while.  Upload Complete.  Environment details for: betz5-env  Application name: betz  Region: us-east-1  Deployed Version: app-7f74-160822_083029  Environment ID: e-3zyk4pueyq  Platform: 64bit Amazon Linux 2016.03 v2.1.3 running Ruby 2.1 (Puma)  Tier: WebServer-Standard  CNAME: UNKNOWN  Updated: 2016-08-22 12:29:03.932000+00:00  Printing Status:  INFO: createEnvironment is starting.  INFO: Using elasticbeanstalk-us-east-1-167880342437 as Amazon S3 storage bucket for environment data.  INFO: Created security group named: sg-9e6fc9e4  INFO: Created load balancer named: awseb-e-3-AWSEBLoa-6TCKNDPQOZUO  INFO: Environment health has transitioned to Pending. Initialization in progress (running for 32 seconds). There are no instances.  INFO: Created security group named: awseb-e-3zyk4pueyq-stack-AWSEBSecurityGroup-1VXHTSO3R625H  INFO: Created Auto Scaling launch configuration named: awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingLaunchConfiguration-CI7ZCOZGHSI  INFO: Added instance [i-03e33a1f265f89c11] to your environment.  INFO: Created Auto Scaling group named: awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingGroup-1CN3N9XS45D1M  INFO: Waiting for EC2 instances to launch. This may take a few minutes.  INFO: Created Auto Scaling group policy named: arn:aws:autoscaling:us-east-1:167880342437:scalingPolicy:67c04326-a636-4870-ad45-b90a1b436646:autoScalingGroupName/awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingGroup-1CN3N9XS45D1M:policyName/awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingScaleUpPolicy-TKX4L47COQH7  INFO: Created Auto Scaling group policy named: arn:aws:autoscaling:us-east-1:167880342437:scalingPolicy:87478c0b-452a-46ab-a23a-4434d4138a10:autoScalingGroupName/awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingGroup-1CN3N9XS45D1M:policyName/awseb-e-3zyk4pueyq-stack-AWSEBAutoScalingScaleDownPolicy-1UGEJG8FXVJPC  INFO: Created CloudWatch alarm named: awseb-e-3zyk4pueyq-stack-AWSEBCloudwatchAlarmLow-BA27Q69FXPNG  INFO: Created CloudWatch alarm named: awseb-e-3zyk4pueyq-stack-AWSEBCloudwatchAlarmHigh-13NTHLWPMZE13  ERROR: [Instance: i-03e33a1f265f89c11] Command failed on instance. Return code: 1 Output: (TRUNCATED)... denied for user 'root'@'ec2-54-204-93-56.compute-1.amazonaws.com' (using password: YES)  /opt/rubies/ruby-2.1.9/bin/bundle:23:in `load'  /opt/rubies/ruby-2.1.9/bin/bundle:23:in `<main>'  Tasks: TOP => db:migrate  (See full trace by running task with --trace).   Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/12_db_migration.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.  INFO: Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].  ERROR: Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.  WARN: Environment health has transitioned from Pending to Degraded. Command failed on all instances. Initialization completed 39 seconds ago and took 6 minutes.    ERROR: The operation timed out. The state of the environment is unknown. The timeout can be set using the --timeout option.  

I realize that I am leaving this quite open-ended, but I have no idea why this is not working or what my next step should be to resolve it. The AWS trouble-shooting docs do not seem to be on point, from what I have been able to find. Thanks for any help.

Ruby on Rails - Remove slug uniqueness from Friendly_id slug in database

Posted: 22 Aug 2016 06:15 AM PDT

I use Friendly_id gem in my application. In my Slide model, I don't need slug to be unique, as it's never duplicated (it's auto generated)

How can I remove sluguniqueness from my slides database.

This is what I have: index_slides_on_slug_and_post_id and slug is :unique => true

awesome_nested_set / acts_as_commentable_with_threading Impossible move in certain views

Posted: 22 Aug 2016 05:43 AM PDT

I have acts_as_commentable_with_threading for comments on a Post model, and my comments work in posts#show but not in comments#show. I've set up the forms with this tutorial by the gem author.

CommentsController

def create      commentable = commentable_type.constantize.find(commentable_id)      @comment = Comment.build_from(commentable, current_or_guest_user.id, body)      @post = commentable      respond_to do |format|        if @comment.save          create_notification @comment          make_child_comment          format.html { redirect_to(:back) }          format.js        else          format.html  { render :action => "new" }        end      end    end      def show      @comment = Comment.find(params[:id])      @post = Post.find_by(id: params[:post_id])      @new_comment = Comment.build_from(@comment, current_or_guest_user.id, "")    end      def make_child_comment      return "" if comment_id.blank?        parent_comment = Comment.find comment_id      parent_comment.errors.full_messages      @comment.move_to_child_of(parent_comment)    end  

PostsController

def show      @post = Post.find(params[:id])      @root_comments = @post.root_comments.paginate(page: params[:page])      @new_comment = Comment.build_from(@post, current_or_guest_user.id, "")         end  

the _reply partial in comments/show and posts/show:

<%= form_for(@new_comment, remote: true) do |f| %>     <%= f.hidden_field :commentable_id, value: @new_comment.commentable_id %>     <%= f.hidden_field :commentable_type, value: @new_comment.commentable_type %>     <%= f.hidden_field :comment_id, value: @comment.id %>      <div class="col-sm-11">      <%= f.text_area :body %>    </div>    <div class="col-sm-1">       <%= button_tag(type: 'submit', class: "btn btn-primary") do %>          <span class="glyphicon glyphicon-comment"></span>        <% end %>    </div>  <% end %>  

Per the guide provided by the gem author, the form in comments/show is the same as the _reply form used in posts#show, which works just fine and creates comments correctly. But when I try to make a comment in comments#show, I get the error

CollectiveIdea::Acts::NestedSet::Move::ImpossibleMove (Impossible move, target node cannot be inside moved tree.):
app/controllers/comments_controller.rb:126:in 'make_child_comment'
app/controllers/comments_controller.rb:17:in 'block in create'
app/controllers/comments_controller.rb:14:in 'create'

even when making a reply to the same comment. (For example, post > comment1 > reply2 is created correctly in posts#show, but comment1 > reply3 in comments#show throws the above error). The params in the server log show that the correct parent_id is being passed from the hidden field, and even if I manually set the parent id in the controller, it still gives an impossible move error. The comment is created in the db, but the parent_id doesn't get set and it isn't properly threaded into the comment tree.

Any help appreciated.

Associations in Ruby on Rails 4

Posted: 22 Aug 2016 06:14 AM PDT

I've got a question to associations in rails. I am trying to create a comment for a post which has a subject. So my routs file looks like this:

resources :subjects do    resources :post do      resources :comments    end  end  

Now am I trying to create a form in the show.html.erb file of the post so someone can create a comment. I've tried it this way which I found in the rails guide:

'posts/show.html.erb'

<%= form_for {[@post, @post.comments.build]} do |f| %>  //fill in form  <% end %>  

'posts.controller.rb'

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

But this gives me an error. If you need any other codeparts, feel free to ask.

Error Message

ActionView::Template::Error (undefined method `post_comments_path' for #<#<Class:0x007f9a4429d5e8>:0x007f9a42c01fc8>):   8:   <strong>Text:</strong>   9:   <%= @post.text %>  10: </p>  11: <%= form_for ([@post, @post.comments.build]) do |f| %>  12:     <p>  13:       <%= f.label :text %><br>  14:       <%= f.text_area :text %>  

Showing two types of currencies in Rails 4 app

Posted: 22 Aug 2016 05:39 AM PDT

I´m building a rails e commerce app, I had all prices in Dollars but now my client want's to show the prices also in Euros.

And the client wants to be able to have different prices for each currency, so I can´t link the dollar amount to the rate of Euro against Dollar to display the prices.

In other words the client must be able to have two inputs to enter prices, one for dollars and one for Euros which are then displayed on the product page.

The only way that I figure to do this is to add another column to the database and call it price_euros or something like that.

Because my lack of experience I wanted to ask here if there is another easier way to do this?

Thanks in advance D

this is the show.html.erbin views/products

<div class="row product_top">        <div class="container">        <% breadcrumb :products %>        <div class="col-xs-12 col-sm-6 center-block">           <div class="product_description">            <h3><%= @product.name %></h3>          <h4><%#=@product.material %></h4>          <p><%= @product.description %></p>          <p class="price"> Designer: </p>          <p><%= @product.designer.designer_name %></p>            <p>In stock: <%= @product.stock_quantity %> </p>       </div>          <div class="col-xs-12">           <p> Price: <%= number_to_currency @product.price, class: 'price' %></p>          </div>          <div class="row add_to_cart">                 <p><%= link_to 'Add to cart', add_cart_path, method: :post %></p>          </div>          </div>         <div class="col-xs-12 col-sm-6 center-block" >      <%= image_tag @product.image.url(:medium), class: "img-responsive"  %>          </div>      <p>    <% if current_user && current_user.admin? %>     <%= link_to 'Edit', edit_product_path(@product) %> |    <% end %>     <%= link_to 'Back',  root_path %>    </p>        </div>      </div>  

This is the _form.html.erbpartial were the admin enter prices

<%= form_for @product, multipart: true do |f| %>    <% if @product.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>          <ul>        <% @product.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>  <div class="container">        <div class="form-group">            <%= f.label :name %><br>            <%= f.text_field :name, class: "form-control", rows: "5" %>        </div>        <div class="form-group">            <%= f.label :designer %><br>            <%= f.select :designer_id, Designer.all.map { |c| [ c.designer_name, c.id ] } %>          </div>        <div class="form-group">            <%= f.label :description %><br>            <%= f.text_area :description, class: "form-control", rows: "5"  %>        </div>        <div class="form-group">           <%= f.label :price %><br>           <%= f.text_field :price %>        </div>        <div class="form-group">           <%= f.label :image %><br>           <%= f.file_field :image %>        </div>         <div class="form-group">           <%= f.label :stock_quantity %><br>            <%= f.number_field :stock_quantity %>        </div>          <div class="form-group">            <%= f.label :category %><br>            <%= f.select :category_id, Category.all.map { |c| [ c.name, c.id ] } %>         </div>          <div class="actions">            <%= f.submit %>          </div>    <% end %>  </div>  

This is my Product model product.rb

class Product < ActiveRecord::Base          mount_uploader :image, ImageUploader            validates_presence_of :name, :price, :stock_quantity      validates_numericality_of :price, :stock_quantity        belongs_to :designer      belongs_to :category      belongs_to :page        def self.search(query)         where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%")       end      end  

this is the product_controller.rb

class ProductsController < ApplicationController    before_action :set_product, only: [:show, :edit, :update, :destroy]    before_filter :initialize_cart    before_action :authenticate_admin!, only: [ :new, :edit, :update, :create, :destroy ]    # GET /products    # GET /products.json    def index      @products = Product.all    end      def search        @products = Product.search(params[:query]).order("created_at DESC")      @categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct      end      # GET /products/1    # GET /products/1.json    def show      end      # GET /products/new    def new      @product = Product.new    end      # GET /products/1/edit    def edit      end      # POST /products    # POST /products.json    def create      @product = Product.new(product_params)        respond_to do |format|        if @product.save          format.html { redirect_to @product, notice: 'Product was successfully created.' }          format.json { render :show, status: :created, location: @product }        else          format.html { render :new }          format.json { render json: @product.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /products/1    # PATCH/PUT /products/1.json    def update      respond_to do |format|        if @product.update(product_params)          format.html { redirect_to @product, notice: 'Product was successfully updated.' }          format.json { render :show, status: :ok, location: @product }        else          format.html { render :edit }          format.json { render json: @product.errors, status: :unprocessable_entity }        end      end    end      # DELETE /products/1    # DELETE /products/1.json    def destroy      @product.destroy      respond_to do |format|        format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_product        @product = Product.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def product_params        params.require(:product).permit(:name, :description, :price, :image, :category_id, :stock_quantity, :designer_id, :query)      end  end  

Elasticsearch Transport Error

Posted: 22 Aug 2016 05:21 AM PDT

So I've run through Heroku's documentation on getting Elasticsearch up and running, and I had it working on another project a few months ago on my current project every time the user adds a record to the application it crashes. If your go back to the index and click "view" the record will be there it's just in the process of saving or searching for the record that the application crashes. The Heroku logs give this error:

Elasticsearch::Transport::Transport::Errors::NotFound ([404] {"error":"Cluster not found. It may take a few moments for new clusters to be created. Please contact support@bonsai.io for further assistance.","status":404}):  2016-08-22T12:13:01.110349+00:00 app[web.1]:   app/controllers/professors_controller.rb:48:in `block in create'  2016-08-22T12:13:01.110349+00:00 app[web.1]:   app/controllers/professors_controller.rb:47:in `create'  

If I run heroku run rake db:migrate it will start up Elasticsearch and successfully migrate the db with no problems. I have Elasticsearch installed on Heroku.

Where can I learn more about SaaS user subscription business logic [on hold]

Posted: 22 Aug 2016 05:21 AM PDT

I am building a SaaS application, I want to learn more about the business logic options available and things I need to build into the application for a good subscription experience.

For example:

  • What happens when credit card is declined
  • What happens when they downgrade the subscription
  • How long should the data be retained in a suspended account

What are the general things that one should be aware of when building a SaaS application? Where can I learn more?

has_one through association or alternative way?

Posted: 22 Aug 2016 06:55 AM PDT

Not sure how to setup the tables and the relationships for what I'm trying to achieve. I thought I need a has_one through relationship but I saw a few posts advising against that.

What I'm trying to achieve is a shop creates a list of their services and their staff select the services they do from this list.

Here's what I have so far:

class User   has_many :staff    # user and shop have relationship via roles (not shown for simplicity)  end    class Shop    has_many :staff    has_many :services    # user and shop have relationship via roles (not shown for simplicity)  end    class Service    belongs_to :shop    has_many :staff through: :staff_services  end    class Staff    belongs_to :shop    belongs_to :user    has_many :services through: :staff_services  end    class StaffService    belongs_to :staff    # ? has_one :service through: :shop    # ? belongs_to :service  end  

I'm not sure how to set the relationship for StaffServices so that a staff is only able to select services from the shop they are a staff member of.

Any help would be appreciated. Thanks!

Ruby on Rails select2 AJAX/JQuery - passing a parameter to controller not working

Posted: 22 Aug 2016 06:54 AM PDT

I'm trying to make a Job descriptions (JD) page to compare between a choose JDs. My main page will have a field to select some jobs, and a button/link to show the selected jobs details in a table below the selection field using select2 with RoR, as in the image Job descriptions Viewer .

My issue is that I cannot pass the selected Jobs IDs to the controller, and I get this message:

Completed 406 Not Acceptable in 20ms (ActiveRecord: 0.0ms) ActionController::UnknownFormat (ActionController::UnknownFormat): app/controllers/job_descriptions_controller.rb:81:in `updateJobs'

My controller method :

def updateJobs    @selected = JobDescription.where(id: params[:selectJdField2])    respond_to do |format|     format.js     format.html     end  end  

The main View (jdComparison.html.erb) will render two partials

<h1>Listing Job Descriptions</h1>  <%= render 'sidebar' %>     <div class="clearfix"></div>  <div>    <%= render partial: 'item_list', locals: { job_desc: @job_descriptions} %>  </div>  

The _sidebar.html.erb partial has selet2 field and a link to refresh the Jds that called "Find Link":

<div class="col-sm-8">  list of JDs:     <%= select_tag "selectJdField", options_from_collection_for_select(@job_descriptions, :id, :job_title), { :multiple => true } %>  </div>  <%= link_to "Find Link", updateJobs_path(@job_descriptions),  :remote => true %>  <script>    $(document).ready(function() { $("#selectJdField").select2(); });  </script>  

The _item_list.html.erb partial will view all JDs have been chosen in the select2 field:

<div>   <table>    <thead>      <tr>       <th>Job title</th>       <th>Department</th>      </tr>    </thead>    <tbody>    <% job_desc.each do |job_description| %>      <tr>        <td><%= job_description.job_title %></td>        <td><%= job_description.department %></td>      </tr>     <% end %>    </tbody>   </table>  </div>  

updateJobs.js.erb, should refresh the JDs list when I click the "Find Link" button (I think my first issue is here)

$("#div_id").html("<%= escape_javascript(render partial: 'item_list', locals: { job_desc: @selected}) %>")  

The JS file (I think my second issue is here):

$ ->   updateLists = () ->    $.ajax      url:'updateJobs'    type: 'post'    dataType: 'html'    format: 'js'    data:   {      selectJdField2 :   $('#selectJdField').val()       }  

The routes:

get 'updateJobs'        =>  'job_descriptions#updateJobs'  post 'updateJobs'        =>  'job_descriptions#updateJobs'  

When I replace the controller method with this:

def updateJobs    @selected = JobDescription.where(id: 1)  end  

it will give me the details of JD number 1 after clicking the Find Link. Kindly, I need your help..

Run a local script on Heroku

Posted: 22 Aug 2016 04:44 AM PDT

I'd like to run an abitrary Ruby script against the rails app (rails console or runner) on my production Heroku instance.

I have researched these articles:

How do I create a ruby script that runs script/console and then runs commands using that environment?

Pass ruby script file to rails console

When I try to run a simple script, I am getting errors.

$ heroku run bundle exec rails runner test.rb --app herokuapp-production  Running bundle exec rails runner test.rb on ⬢ herokuapp-production... up, run.2390  /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands/runner.rb:62:in `test': wrong number of arguments (given 0, expected 2..3) (ArgumentError)  

The script is

image = Image.find(4305)  puts "wget --output-document image-#{image.product_id}.jpg #{image.data.url(:xlarge)} "  

Rails: Polymorphic type relation or not?

Posted: 22 Aug 2016 04:14 AM PDT

I have three tables below.

Those are basically "Class Table Inheritance".

  • Invoices
  • CardInvoices
  • BanktransferInvoices

```

Invoices  --------  - id  - total_amount  - invoiceable (either a CardInvoice *or* a BanktransferInvoice)    CardInvoices  --------  - id  - fee_amount  - gateway_error  - ...      BanktransferInvoices  --------  - id  - ...  

```

Basically this is a has_one relation Invoice => BankInvoice/CardInvoice.

But I have to extract from other tables and insert data to those tables. (ETL things.) So I do use raw SQL to insert data.

So I doubt the "Polymathic type model" above is clean or not, because

First, metadata has to be inserted to make it work. (Ex. Invoice_type)

Second, Constraints can't be applied.

Third, Direct join doesn't work.

So I'm thinking about changing the pointing direction.

Invoice <= BankInvoice / CardInvocie

With this, I can use the direct join, and check the constraint.

Now question is,

With the second way, how can I retrieve with BankInvoice / CardInvoice efficiently in Rails 4.2? (I'm new to Rails. I think left outer join would be good. But the more Invoice types added, the more overhead there are.)

or can you suggest which implementation would be the better solution and why.

Thanks,

How to override set_login in spree model user.rb?

Posted: 22 Aug 2016 07:47 AM PDT

In spree sign_up the app/models/spree/user.rb has

def set_login    # for now force login to be same as email, eventually we will make this configurable, etc.    self.login ||= self.email if self.email  end  

How can I override set login and do something like this:

def set_login    # for now force login to be same as email, eventually we will make this configurable, etc.    self.login ||= self.phone if self.phone  end  

Thanks in advance

Infobox of google map restricting jquery Hover function

Posted: 22 Aug 2016 03:28 AM PDT

I have included some html and erb code inside infobox.setContent function,i have written hover function for those html div classes using jquery but background color is not changing when i hover on that button and i am not getting any error also? Does any one know about it please help me out.

Not displaying ajax response in haml

Posted: 22 Aug 2016 03:27 AM PDT

I am trying to display response from the rails server in a div.

ajax call is like this

$.get('/news/search?search=' + existingString, function(data) {    $("#results").html("");    console.log(data);    len=data.length;    $('#result').append('#{escape_javascript(render("newsdisplay") )}');  

_newsdisplay.html.haml

- if @results    - @results.each do |anzen|      %li.clearfix.postMain.allnews       .wrapper         %li          .messaIcon            .icon              %img{:src => anzen.news_image.thumb.url}          .messaCon            .areaDay.clearfix              %p.messaTextCon              グループ名:              %span= anzen.news_name  

search action

def search    if params[:search].present?      @results = News.search(params[:search])    end  end  

routes.rb

get 'news/search', to: 'news#search', as: :newssearch  

I am getting the response from the server correctly. But no change in the page.But in console the full page with rendered response is displayed. Can anyone guess the issue

Ruby on rails : undefined method `map' for nil:NilClass , what causes this? when i add record to table

Posted: 22 Aug 2016 05:06 AM PDT

here is my _form.html.erb

<%= simple_form_for @book,:html => { :multipart => true }  do |f| %>  <%= select_tag(:category_id, options_for_select(@categories), :promt => "Select a category") %>  <%= f.file_field :book_img %>  <%= f.input :title, label: "Book Title" %>  <%= f.input :description %>  <%= f.input :author %>  <%= f.button :submit %>  

and here is my BooksController

class BooksController < ApplicationController    before_filter :initialize_book  before_action :find_book, only: [:show, :edit, :update, :destroy]    def initialize_book      @book = Book.new  end      def show      @book =Book.find(params[:id])  end    def index      if params[:category].blank?          @books = @books = Book.all.order("created_at DESC")      else          @category_id = Category.find_by(name: params[:category]).id          @books = Book.where(:category_id => @category_id).order("created_at DESC")      end       end    def new      @book = current_user.books.build  # Book.new       @categories = Category.all.map{ |c| [c.name, c.id]}   end    def create      @book =current_user.books.build(book_params)  # Book.new(book_params)       @book.category_id = params[:category_id]      if @book.save          redirect_to root_path      else          render 'new'      end  end    def edit      @categories = Category.all.map{ |c| [c.name, c.id]}   end    def update      @book.category_id = params[:category_id]      if @book.update(book_params)          redirect_to book_path(@book)      else          render 'edit'      end  end    def destroy      @book.destroy      redirect_to root_path  end    private      def book_params          params.require(:book).permit(:title, :description, :author, :category_id, :book_img)      end        def find_book          @book =Book.find(params[:id])      end  

end

book.rb

class Book < ActiveRecord::Base  	belongs_to :user  	belongs_to :category  	has_attached_file :book_img, styles: { book_index: "250x250>", book_show: "325x475>" }, default_url: "/images/:style/missing.png"    	validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/  end

I installing the paperclip gem to add image to Book and this is a file created when i run Rails migration generator: rails generate paperclip Book book_img

class AddAttachmentBookImgToBooks < ActiveRecord::Migration    def self.up      change_table :books do |t|        t.attachment :book_img      end    end      def self.down      remove_attachment :books, :book_img    end  end

But when i add Book and attrack an image to Book had show an error

NoMethodError in Books#create  Showing C:/Sites/BookReview/app/views/books/_form.html.erb where line #2 raised:    undefined method `map' for nil:NilClass  Trace of template inclusion: app/views/books/new.html.erb    Rails.root: C:/Sites/BookReview    Application Trace | Framework Trace | Full Trace  app/views/books/_form.html.erb:2:in `block in _app_views_books__form_html_erb___232429848_42489936'  app/views/books/_form.html.erb:1:in `_app_views_books__form_html_erb___232429848_42489936'  app/views/books/new.html.erb:3:in `_app_views_books_new_html_erb__358042162_78928608'  app/controllers/books_controller.rb:39:in `create'  Request    Parameters:    {"utf8"=>"✓",   "authenticity_token"=>"kuaFBEmKqeVwLRr+NWke5AS5GxqPK0O/rOSPwDrc+8GsERzW0AlTJvhUji8/OevAIYhETyKc+jiNC3XIvpTAxQ==",   "category_id"=>"3",   "book"=>{"book_img"=>#<ActionDispatch::Http::UploadedFile:0x91a4060 @tempfile=#<Tempfile:C:/Users/muitr/AppData/Local/Temp/RackMultipart20160822-11652-1id5vn1.jpg>,   @original_filename="csharp.jpg",   @content_type="image/jpeg",

Rails I18n fallbacks for hash

Posted: 22 Aug 2016 02:57 AM PDT

I have an example ymls:

en:    hello:      world: World      time:        am: "AM"        pm: "PM"    ja:    hello:      world:      time:        am: "午前"        pm: "午後"  

Fallback working well when I'm trying to call missing locale:

I18n.locale = :ja  I18n.t('hello.world') => 'World'  

But it returns 'nil' on some values when I'm calling for parent key (hello):

I18n.locale = :ja  I18n.t('hello') => { world: nil, time: { am: "午前", pm: "午後" } }  

How can I get translations with fallbacks: { world: 'World', time: { am: "午前", pm: "午後" } }

Thanks!

What's the best way to create recurring payments of variable amount in Stripe?

Posted: 22 Aug 2016 02:59 AM PDT

I have an online club which needs to invoice its users each month. Recurring payments looks great for this, however they are based on "Plans" where I set up different defaults and the user subscribes to a plan. My users can pay anything between $2 and $200 and those amounts might vary depending on the month since it's recurring products they're buying.

Does anyone have any good suggestions on how I can to this in Stripe? So far all i've come up with is invoicing & account balance. Which means shoehorning the user into a subscription plan that is near their payment and then adding a negative or positive balance to cover the rest. However I'm certain this isn't the best way (in fact. I think it's a really bad way)

Any help would be appreciated

Routing Error - Paperclip

Posted: 22 Aug 2016 03:12 AM PDT

For some reason when I upload files using paperclip, and then try to download them I get this error: No route matches [GET] "/Users/Luka/RailsApps/hsc_notes/public/system/documents/pdfs/19/Wilfred_Owen_Essay.docx"

It is saying that it cant get the file. The weird thing is, is that that file is actually in that path. In other words, when i open /Users/Luka/RailsApps/hsc_notes/public/system/documents/pdfs/19/Wilfred_Owen_Essay.docx in safari, it sends me to the correct document.

I cannot figure out why it is not downloading the file?

This is the relevant bit from my documents model:

if Rails.env.development?      has_attached_file :pdf, :use_timestamp => false,                  :url => ":rails_root/public/system/documents/pdfs/:id/:basename.:extension",                  :path => ":rails_root/public/system/documents/pdfs/:id/:basename.:extension"      validates_attachment_content_type :pdf, :content_type => ["application/pdf","application/vnd.ms-excel",                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",           "application/msword",            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",            "text/plain"]    else      has_attached_file :pdf, :use_timestamp => false      validates_attachment_content_type :pdf, :content_type => ["application/pdf","application/vnd.ms-excel",                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",           "application/msword",            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",            "text/plain"]  end  

Embedding precompiled Angular Offline app into rails

Posted: 22 Aug 2016 02:28 AM PDT

I have a rails application where one little part has to work offline. This part can be totally independent, so I chose to let someone else do it outside of the rails stack as an independent angular offline-application that uses the rails application via REST. The angular app will be a precompiled app with a application.manifest file.

Now I want to include it into the rails application just to deploy one app instead of two on the clients server.

Example:

I have the rails application with administrational stuff and when the user visits something like /coaching the angular app should be served.

Now my questions are:

Do I put the angular app into the /public folder? Do I have to add some sort of route or add the manifest to application.js or something like that? Or do I add a controller action that responds to "application.manifest"?

Thanks in advance, Jascha

rake task in upstart service (sphinxsearch)

Posted: 22 Aug 2016 02:25 AM PDT

I am failing at making the Sphinx daemon run automatically at boot.

When I do it manually it does work (and this is what I am trying to reproduce in my upstart script):

  1. I log in as deploy user
  2. cd sharetribe
  3. bundle exec rake RAILS_ENV=production ts:index and I wait for it to end, then:
  4. bundle exec rake RAILS_ENV=production ts:start and the worker is now running

Here is my upstart script:

 start on runlevel [2345]   stop on shutdown     chdir  /home/deploy/sharetribe   env RAILS_ENV=production   script       echo $$ > /var/run/sphinxboot.pid       sudo -u deploy -s -- "cd /home/deploy/sharetribe; bundle exec rake RAILS_ENV=production ts:index; bundle exec rake RAILS_ENV=production ts:start"   end script     pre-start script       echo "[`date`] Sphinx Worker Starting" >> /var/log/sphinxboot.log   end script     pre-stop script       rm /var/run/sphinxboot.pid       echo "[`date`] Sphinx Worker Stopping" >> /var/log/sphinxboot.log   end script  

Thank you for your help

No comments:

Post a Comment