Sunday, May 8, 2016

Rails 4 - where to store temporarily files? | Fixed issues

Rails 4 - where to store temporarily files? | Fixed issues


Rails 4 - where to store temporarily files?

Posted: 08 May 2016 06:57 AM PDT

I am generating txt/pdf documents, saving them (currently) in the /tmp directory, uploading them to Amazon S3 and then removing them from the /tmp directory.

The problem is that when I deploy some new code while a new file being currently generated, the process of generating is interrupted, because the file is removed from the /tmp directory.

Where is the best to store temporary documents within the Rails system?

Know what event triggered the after_commit of an ActiveRecord model

Posted: 08 May 2016 06:43 AM PDT

I have the following snippet:

class Product   after_commit :do_something, on: %i(update create)     def do_something     if # update       ...     else # create       ...     end   end  end  

How to know what event triggered the after commit here?

Please don't tell me to have 2 after commits like:

after_commit :do_something_on_update, on: :update  after_commit :do_something_on_create, on: :create  

RSpec failure ( undefined method `id' for nil:NilClass ) with has_many through model

Posted: 08 May 2016 06:31 AM PDT

I can't make the spec to pass in the relationships controller. I have to change something about my object in the controller or the controller_spec. Feel free to ask any doubt about my controller... thanks

user.rb

class User < ActiveRecord::Base      # Associations    has_many :active_relationships, class_name:  "Relationship",                                    foreign_key: "follower_id",                                    dependent:   :destroy    has_many :passive_relationships, class_name:  "Relationship",                                    foreign_key: "followed_id",                                    dependent:   :destroy    has_many :following, through: :active_relationships, source: :followed    has_many :followers, through: :passive_relationships, source: :follower      # Follows a user.    def follow(other_user)      active_relationships.create(followed_id: other_user.id)    end      # Unfollows a user.    def unfollow(other_user)      active_relationships.find_by(followed_id: other_user.id).destroy    end      # Returns true if the current user is following the other user.    def following?(other_user)      following.include?(other_user)    end  end  

relationships_controller.rb

class RelationshipsController < InheritedResources::Base      def create      user = User.find(params[:followed_id])      current_user.follow(user)      redirect_to user    end      def destroy      user = Relationship.find(params[:id]).followed      current_user.unfollow(user)      redirect_to user    end  end  

relationships_controller_spec.rb

require 'rails_helper'    describe RelationshipsController do    let(:relationship) { create(:relationship) }    let(:user) { create(:user) }      before do      sign_in :user, create(:user)    end      describe '#create' do      let!(:followed) { create(:user) }      it "should require logged-in user to create relationship" do        expect{          post :create, followed_id: followed.id        }.to change(Relationship, :count).by(1)        redirect_to root_path      end    end      describe '#destroy' do      let!(:relationship) { create(:relationship) }        it "should require logged-in user to destroy relationship" do        expect {          delete :destroy, id: relationship.id        }.to change(Relationship, :count).by(-1)        redirect_to root_path      end    end  end  

Failures:

  1) RelationshipsController#destroy should require logged-in user to destroy relationship       Failure/Error: active_relationships.find_by(followed_id: other_user.id).destroy         NoMethodError:         undefined method `id' for nil:NilClass  

values not saving with has_many through association

Posted: 08 May 2016 06:47 AM PDT

For my Room edit form, I'm trying to associate 2 has_many through relationships with the same models (Color and Room)

where is my join model migration :

color_preferences

class CreateColorPreferences < ActiveRecord::Migration    def change      create_table :color_preferences do |t|        t.references :color        t.references :room        t.string :value          t.timestamps null: false    end  end  

end

The column "value" can have these values:

  • Love
  • Hate

I have the following models with the current relationships :

room.rb

class Room < ActiveRecord::Base     has_many :color_preferences     has_many :colors, through: :color_preferences     accepts_nested_attributes_for :color_preferences  end  

color.rb

class Color < ActiveRecord::Base      has_many :color_preferences    has_many :rooms, through: :color_preferences  end  

and my join model :

color_preference.rb

class ColorPreference < ActiveRecord::Base      belongs_to :color    belongs_to :room    end  

my controller :

rooms_controller.rb :

class RoomsController < ApplicationController      before_action :set_room, only: :edit      def edit      @love_colors = if @room.color_preferences.where(value: "love").present?        @room.color_preferences.where(value: "love")      else        @room.color_preferences.build      end      @hate_colors = if @room.color_preferences.where(value: "hate").present?        @room.color_preferences.where(value: "hate")      else        @room.color_preferences.build      end    end      private      def set_room      @room = Room.find(params[:id])    end      def room_params      params.require(:room).permit(color_preferences_attributes: [:id, :value, color_id: []])    end  end  

and my view :

room/edit.html.haml

= simple_form_for @room do |f|    = f.simple_fields_for :color_preferences, @love_colors do |cp|      = cp.association :color, as: :check_boxes      = cp.hidden_field :value, value: "love"    = f.simple_fields_for :color_preferences, @hate_colors do |cp|      = cp.association :color, as: :check_boxes      = cp.hidden_field :value, value: "hate"  

If I look at the parameters I have the following :

"room"=>{"color_preferences_attributes"=>{"0"=>{"color_id"=>["11", "12", "13", ""], "value"=>"love"}, "1"=>{"color_id"=>["1", "2", "3", ""], "value"=>"hate"}}  

But colors aren't save in the ColorPreferences Table :

[#<ColorPreference id: 1, color_id: nil, room_id: 1, value: "love", created_at: "2016-05-08 12:55:29", updated_at: "2016-05-08 12:55:29">...]  

My two questions are :

  • What's wrong with my setup not saving color_id values ?
  • Did I set my edit method correctly in order to retrieve color values in my form? In fact If I set a color id for a specific entry I didn't get the value selected. Thanks =)

Rails form calling the wrong method

Posted: 08 May 2016 06:18 AM PDT

I'm new to rails and i'm using the bootstrap simple form to update a user's information but it keeps calling the wrong controller.

Code for the form:

simple_form_for(@user) do |f|  = f.input :forename  = f.input :surname  .form-actions    = f.button :submit, :method => :update  

Code in the controller:

def update    if @user.update(user_params)      redirect_to home_path    else      redirect_to wrong_path  end  

but in another page I use the form again in a different controller called AdminController the update form calls the AdminController instead of the UserController.

What do i need to get it to call the correct controller/

rails page navigation through side menu bar

Posted: 08 May 2016 06:14 AM PDT

I am working on an application and here I have a side menu bar (image is attached here)here is the link of screenshot.

what I want is to navigate through this menu, actually I want this menu to be preset on every page mentioned in menu list. And also there should be focus on link on which I am currently on. here I have attached screenshot of that too.

I was thinking to repeat my side nav menu code on all the pages on menu. But It won't active/focus the currently active link. Any better solutions? What should I do to solve this issue?

Gmaps4rails - how to set map style based on zoom

Posted: 08 May 2016 05:30 AM PDT

I want to change the style of my map based on the zoom level so road names only appear when the map is zoomed in alot. I've found this example although it isn't implemented in gmaps4rails.

Google-Maps v3: How to change the map style based on zoom level?

I've managed to get the example to work in a simple implementation outside of gmaps4rails however when I try to implement it inside my existing code with gmaps4rails I get the error

Uncaught TypeError: Cannot read property 'set' of undefined

The code from my gmaps4rails implementation is below. Does anyone have any ideas how to fix this or if there is a better way to go about creating the result I am looking for?

this.buildMap = function(markers) {    handler = Gmaps.build('Google', {       builders: { Marker: InfoBoxBuilder }    });      handler.buildMap({      provider: {        zoomControl: true,        clickableIcons: false,      },      internal: {        id: 'map',      }    },     function() {      markers = handler.addMarkers(markers);      handler.bounds.extendWith(markers);      handler.fitMapToBounds();      handler.getMap().setZoom(12);        //Close infowindow on click anywhere on page      google.maps.event.addListener(handler.getMap(), 'click', function() {        handler.currentInfowindow().close();      });        // Change map style based on zoom level      var mapStyleZoomedOut = [        {           featureType: "road",          elementType: "labels",          stylers: [            { visibility: "off" }          ]         }];       var mapStyleZoomedIn = [        {           featureType: "road",          elementType: "labels",          stylers: [            { visibility: "on" }          ]         }];        var styledMapOptions = {map: handler, name: 'minimial'};       var styledMapOptions2 = {map: handler, name: 'maximial'};         var sMapType = new google.maps.StyledMapType(mapStyleZoomedOut,styledMapOptions);       handler.mapTypes.set('minimial', sMapType);       handler.setMapTypeId('minimial');         var sMapType2 = new google.maps.StyledMapType(mapStyleZoomedIn,styledMapOptions2);       handler.mapTypes.set('maximial', sMapType2);        google.maps.event.addListener(handler.getMap(), 'zoom_changed', function() {         var zoomLevel = handler.getZoom();        var sMapType;        // === IF Zoom Level <= 14 use mapStyleZoomedIn         if(zoomLevel <=14)          handler.setMapTypeId('minimial');        // === If Zoom Level > 14 use mapStyleZoomedOut         else          handler.setMapTypeId('maximial');       });      });  

How to create many single select inputs for a has_many association on simple form?

Posted: 08 May 2016 05:35 AM PDT

I've created a form using Simple Form in Rails to create new tests. My Test model has a has_and_belongs_to_many association with the Tool Model.

My code gets all tools and groups them into categories (a category is an attribute of a tool). It then creates a single select box for each category (as shown in the image).

- all_tools = Tool.all.group_by(&:category)    - all_tools.each do |category|      = f.association :tools,        collection: category.last,        label: category.first,        label_method: lambda { |tool| "#{tool.name} (#{tool.description})"},        input_html: { multiple: false }  

Many select boxes

When choosing a tool from each select box and submitting the form, I get the following error:

found unpermitted parameter: tool_ids  

and the there's only one id currently being submitted for the tool_ids instead of an array of ids which I need.

I know this works when the boxes are multiple selects but I only want the user to be able to select one tool from each category and have it submit all tool_ids in an array similar to the way it would if the user was selecting them from a multiple select box.

So my question is, how can I use multiple single select boxes to submit an array of tool_ids in Simple Form?

EDIT: As requested, I've added the relevant code:

tests_controller:

def create    @test = Test.new(test_params)    @tools = Tool.all.select(:name).distinct    if @test.save        Activity.log(current_user, "Created test #{@test.id}")        redirect_to @test, notice: 'Test was successfully created.'    else      render :new, notice: 'Unable to save Test Details.'    end  end    private    # Only allow a trusted parameter "white list" through.  def test_params    params.require(:test).permit(      :date,      :start_time,      :description,      :machine,      :location,      :feeder_screw_diameter,      :notes,      :user_id,      :tool_ids => [],      :powder_ids => []    )  end  

Log output when submitting:

Started POST "/tests" for 127.0.0.1 at 2016-05-08 13:24:52 +0100  Processing by TestsController#create as HTML    Parameters:       {"utf8"=>"✓","authenticity_token"=>"WKw+tQ1WKyxW7XZWCDvbvShCKnZ7iMY597P8eDGIvZEyis4ks7Mf4Lcu4vCf7q+fwtsReocmAlMGUrrhI4SgdQ==",    "test"=>{"start_time(1i)"=>"2016",    "start_time(2i)"=>"5",    "start_time(3i)"=>"8",    "start_time(4i)"=>"13",    "start_time(5i)"=>"23",    "description"=>"Test",    "machine"=>"Some machine",    "location"=>"Some Place",    "feeder_screw_diameter"=>"15",    "tool_ids"=>"21",    "powder_ids"=>["", "3"],    "user_id"=>"1",    "date"=>"11-05-2016",    "notes"=>"Some Notes"},    "button"=>""}    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]  Completed 500 Internal Server Error in 14ms (ActiveRecord: 0.4ms)  ** [Airbrake] Notice was not sent due to configuration:             Environment Monitored? false             API key set? true    ActionController::UnpermittedParameters (found unpermitted parameter: tool_ids):    app/controllers/tests_controller.rb:201:in `test_params'    app/controllers/tests_controller.rb:70:in `create'        Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.0ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.7ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (12.9ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (7.9ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.2ms)    Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (16.1ms)  

Many thanks for any help!

Tell controller to take request as JS

Posted: 08 May 2016 04:40 AM PDT

In a single-page app, all articles are loaded via AJAX. The feature I am now implementing will allow the user to navigate through the articles, again, remaining on a single page.

Thing is, when I click the next article button the controller takes the request as an HTML request. What I would like to do, of course, is to tell the controller to take this request as JS.

How does one accomplish that?

I'll paste in some code.

#log  Started GET "/headlines/5/articles/50" for ::1 at 2016-05-08 04:07:05 -0700  Processing by ArticlesController#show as HTML    #articles_controller.rb  def show       @next_article = @article.next      respond_to do |format|          format.js { render :partial => "article" }       end  end    #_article.haml  - if Article.exists?(@next_article)    = link_to 'Next', [@next_article.headline, @next_article]      #articles.js  $(document).ready(function() {    $('.ajax_load').each(function(index, element) {      var url = $(element).data('remote-url')      if (url) {        $.get(url, function(content) {          $(element).html(content);            }, 'html')      } else {        console.log("missing url for ajax!")    }   })  })    #index.haml  .ajax_load.article-content{ data: { 'remote-url' => headline_article_path(headline, article) }, id: "article" }  

The action 'destroy' could not be found for MessagesController 1

Posted: 08 May 2016 05:36 AM PDT

I keep getting the error destroy action can not be found in the messagesController. But i have the destroy action setup i don't get why i am getting this message error. Can some one tell me why i can getting this error?

class MessagesController < ApplicationController    before_action :find_message, only: [:show, :edit, :update, :destroy]    def index      @messages = Message.all.order("created_at DESC")    end      def show     end      def new      @message = Message.new    end      def create      @message = Message.new(message_params)      if @message.save        redirect_to root_path      else        render 'new'      end        def edit      end        def update        if @message.update(message_params)          redirect_to message_path        else          render 'edit'        end      end        def destroy        @message.destroy        redirect_to root_path      end    end    private      def message_params      params.require(:message).permit(:title, :description)    end      def find_message      @message = Message.find(params[:id])    end  end  

In edit action form, hide an form fieild

Posted: 08 May 2016 04:38 AM PDT

Have an rails application wherein I don't want some of the form fields to appear in my edit action form. How can I go about doing this in rails?

Cannot get to edit view to modify profile

Posted: 08 May 2016 03:24 AM PDT

trying to edit user profile:

in _footer (link_to "Edit profile", edit_user_path):

<% if current_user %>      <% if admin? %>        <%= link_to "Admin Page", admin_users_path %> Signed in as <%= current_user.username %> <%= link_to "Edit profile", edit_user_path %>(<%= link_to "Log out", session_path("current"), method: :delete %>) etc  

in Users controller:

 def edit      @user = current_user      end  

in user edit view:

    <%= form_for @user do |f| %>        <% if @user.errors.any? %>  etc  

routes:

resources :users, only: [:new, :create, :edit]  

i'm obviously missing some key concept, points to another controller altogether: ActionController::UrlGenerationError in Movies#index,

No route matches {:action=>"edit", :controller=>"users"} missing required keys: [:id]

just wondering how this is wrong, thanks!

Rails Adding multiple records at once

Posted: 08 May 2016 03:46 AM PDT

When I add a product to the cart in my online store , added several entries in the database , and each time a different number . Did anyone this problem? Typically, once added 2 entries , but sometimes 5-6.

class Fe::CartLineItemsController < ApplicationController    include CurrentCart    before_action :set_fe_cart_line_item, only: [:show, :edit, :update, :destroy, :increment, :decrement]    before_action :set_cart, only: [:create]      ...        def create      part = Part.friendly.find(params[:part_id])      @fe_cart_line_item = @cart.add_part(part.id)        respond_to do |format|        if @fe_cart_line_item.save          format.html { redirect_to :back }          format.js          format.json { render action: 'show',            status: :created, location: @line_item }        else          format.html { render action: 'new' }          format.json { render json: @line_item.errors,            status: :unprocessable_entity }        end      end    end      ...        private        def set_fe_cart_line_item        @fe_cart_line_item = CartLineItem.find(params[:id])      end        def fe_cart_line_item_params        params.require(:fe_cart_line_item).permit(:part_id, :cart_id, :q)      end  end        class Fe::CartsController < ApplicationController    include CurrentCart    before_action :set_cart, only: [:show, :edit, :update, :destroy]      ...        def create      @cart = Cart.new(cart_params)        respond_to do |format|        if @cart.save          format.html { redirect_to @cart, notice: 'Cart was successfully created.' }          format.json { render :show, status: :created, location: @cart }        else          format.html { render :new }          format.json { render json: @cart.errors, status: :unprocessable_entity }        end      end    end      ...       private        def cart_params        params.fetch(:cart, {})      end  end        // current_cart.rb    ...    def set_cart      @cart = Cart.find(session[:cart_id])    rescue ActiveRecord::RecordNotFound      @cart = Cart.create      session[:cart_id] = @cart.id    end    ...          //cart.rb        ...        def add_part(part_id)          current_item = cart_line_items.find_by(part_id: part_id)          if current_item            current_item.q += 1          else            current_item = cart_line_items.build(part_id: part_id)            current_item.price = current_item.part.cost_1          end          current_item        end  ...  

RoR engine alternative for Django [on hold]

Posted: 08 May 2016 02:44 AM PDT

Could somebody know alternative RoR engine(miniature applications that provide functionality to their host applications) for Django? Or some techniques for splitting your django app.

What inverse_of do in Rails belongs_to association?

Posted: 08 May 2016 04:12 AM PDT

First, I know how inverse_of works in has_many association.

# relationship without inverse_of  user has_many :orders    # this will generate two database queries  user.orders.first.user  Order Load (0.1ms)  SELECT  `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2  ORDER BY `orders`.`id` ASC LIMIT 1  User Load (0.1ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1  

Here, user and user.order.first.user are two different object.

And with inverse_of

# relationship with inverse_of  user has_many :orders, inverse_of: :user    # this will generate just one database query  user.orders.first.user  Order Load (0.1ms)  SELECT  `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2  ORDER BY `orders`.`id` ASC LIMIT 1  

Now, user and user.order.first.user are the same object.

But, what inverse_of does in this belongs_to associstaion?

# relationship with inverse_of in belongs_to association  order belongs_to :user, inverse_of: :orders    order.user.orders  # will generate two database queries  User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1  Order Load (0.1ms)  SELECT `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2  

There are no difference if I use inverse_of or not use inverse_of in this relationship. So, maybe I use it in a wrong way? what's the point of inverse_of in belongs_to association?

Rails assets manifest file not found

Posted: 08 May 2016 02:06 AM PDT

I'm trying to do an initial deploy on to a server and it keeps failing. enter image description here

I'm not entirely sure what the manifest file is. My public folder only has the error pages.

Does anyone have any idea why this is happening?

Thanks!

Pass parameters in AccessToken post request for gem Oauth rails

Posted: 08 May 2016 01:31 AM PDT

Hi I am trying do POST API call for AccessToken class of gem Oauth. But I am getting weired responses so can any please let me know what is the exact way for making post call.

Implementation 1:

access_token.post('/organizations/223031/files', { 'name' => '10.3.199_export.zip' }.to_json(),  { 'Accept'=>'application/vnd.deere.axiom.v3+json', 'Content-Type' => 'application/vnd.deere.axiom.v3+json' })  

For this call I am getting 403 error

Implementation 2:

access_token.post('/organizations/223031/files',  :body => {:name => 'xyz.zip'}.to_json,  :headers => { 'Content-Type' => 'application/vnd.deere.axiom.v3+json', 'Accept'=>'application/vnd.deere.axiom.v3+json'})  

For this call I referred this link, but getting the 404 error.

So I have a following doubts

  • As per my understanding implementation 1 is correct (correct me if I am wrong) as for this getting the 403 where as for implementation 2 getting the 404 error. So what is the actual difference between them.
  • What is the best way for this.

Rails database schema for saas application

Posted: 08 May 2016 01:25 AM PDT

I am working on rails project which is a saas app. I am just beginning with rails and comparatively new to web development. I am not able to decide database schema.

I am modeling a typical sass app which will have users, property, billing plans, etc. What would be best db architecture to for this associations. It should have

  • users can have many properties
  • properties can belongs to many users
  • there should be billing plan

An example would be Moz app or skylight or newrelic. Any advice on how should I go forward with this ?

Make Rails table column attribute read only

Posted: 08 May 2016 01:47 AM PDT

What is the best way to make my table column read only? disable the setter method? The column is set by postgres trigger, so I don't want to set it in the application level

Strings (by themselves) not permitted in JSON responses?

Posted: 08 May 2016 01:38 AM PDT

I'm trying to understand what is incorrect with a JSON response being a string.

Does not work:

render json: "downgrade"  

Error:

SyntaxError: Unexpected token d in JSON at position 0

This works:

render json: {recommendation: "downgrade"}  

This works:

render json: ["downgrade"]  

Even this works:

render json: 17  

Why would an integer by itself work but a string would not? Or does render json: "downgrade" need to be written differently.

[Note: this is being sent from a Rails backend]

Image requests are sent with cookies set by other domains after enabling CORS via Rack CORS Middleware. How to stop it

Posted: 08 May 2016 12:36 AM PDT

I am using Rack CORS gem to enable cross origin request for my Rails app. When there is an image request to my app, I can see that it has "Cookie" header attached along with it which has cookie data set by other domains (Eg: Google Analytics). I don't want this header data. How to stop sending this header in the request?

Below is by config code in application.rb,

config.middleware.insert_before 0, "Rack::Cors" do    allow do      origins '*'      resource '*', :headers => :any, :methods => [:get, :post, :options]    end  end  

Does :headers => :any has something to do with this?

I have gone through this question . But have no idea how to block third party cookies. Help is much appreciated.

How to grab videos from Udemy in Ruby on Rails? [on hold]

Posted: 07 May 2016 11:29 PM PDT

I am looking for a way to grab videos from Udemy.com and download them. How to do it in Ruby on Rails ?

Please explain the main idea and mention all needed gems.

Return array of values instead of array of objects from SQL query in Rails

Posted: 07 May 2016 10:34 PM PDT

I have a SQL query in a Rails model that responds with an array of objects. And each object has an attribute called points with a value.

But its preferable for query to just return an array of points like [10,15,5] instead of [object,object,object] which requires then extracting the points out into another array to be useful.

Model file

LAST_3_SELECT = "    SELECT      (        (data.ap / (data.apa * 1.0))        +        (data.vp / (data.vpa * 1.0))      )      / 2 * 1.5 * data.level      AS points    FROM data    WHERE data.user_id = ?    GROUP BY data.id    ORDER BY data.created_at DESC    LIMIT 3  "    def self.last_3(user_id)    connection.select_all(sanitize_sql_array( [LAST_3_SELECT, user_id]), "last-3")  end  

Is this possible to do in a query itself, or necessary to do in a method outside it?

I don't have much experience writing raw SQL queries into Rails methods so any guidance would be very appreciated.

How to install ImageMagick on Windows 8?

Posted: 07 May 2016 11:48 PM PDT

I'm trying to setup ImageMagick so I can use the Paperclip gem for Ruby on Rails. I've looked at pretty much every question on StackOverflow about the issue, but they all just skip over my issue, that none of the ImageMagick commands are recognized on the CommandPrompt.

I downloaded and then installed ImageMagick-7.0.1-1-Q16-x64-dll.exe on this page

I installed the program to my C: directory, so that there wouldn't be an issue with spaces in the Path, and I used all default installation selections and even selected "Install development headers" which some answers said to do. My issue is that when ImageMagick finishes installing, and it says to test some commands (like "convert -version) on Command Prompt, they all result in

"'convert' is not recognized as an internal or external command ...."

On the command prompt. What could be an issue? Every step-by-step tutorial automatically assumes that these commands are recognized. Most troubleshooting involves steps afterwards.

Here's the documentation for paperclip. All I have to do is make sure the gem has access to ImageMagick, by putting in the development.rb file:

Paperclip.options[:command_path] = "/usr/local/bin/"

In order to find that path above, however, the documentation says to type "which convert". I've researched this and apparently that's a Unix command, and not something for Windows.

So basically, what steps do I need to take so that paperclip has access to ImageMagick? Why aren't basic ImageMagick commands recognized, even after a completed installation?

Rails Render JSON of a has_many, through Association

Posted: 07 May 2016 10:08 PM PDT

I have 3 Models in my application Artists, Albums and Songs

class Artist < ActiveRecord::Base      has_many :albums      has_many :songs, :through => :albums  end    class Albums < ActiveRecord::Base      has_many :songs      belongs_to :artist  end    class Albums < ActiveRecord::Base      belongs_to :albums  end  

How do render it as JSON wherein it returns an array of the Artists, each artist with a property 'Albums' wherein it is an array of the Albums for each artist and each album has a property Songs which is an array of songs for each album. Like this

[ {      id: 1,      name: Artist_Name,      albums: [          {              id: 1,              name: Album_Name,              songs: [{                  id: 1,                  title: Song_Title,                  lyrics: Song_Lyrics              }]          }      ]  }]  

Rails 4.2: rendering collection_check_boxes in Ajax response results in non-html_safe content

Posted: 07 May 2016 11:55 PM PDT

I am using Rails 4.2. I have a "new projects" page on which there is a form to create a new project. There is also a second form on the page that allows the user to add users to the project through Ajax. The Ajax is working, but I am having issues rendering the response correctly.

The "new project" form shows the available users as a list of checkboxes, created by this snippet:

<div id="disclosed_users_check_box_list">    <%= f.collection_check_boxes :disclosed_user_ids, User.order(:first_name, :last_name), :id, :name_with_job_title do |b| %>      <%= b.check_box %> <%= b.label %><br>    <% end %>  </div>  

The "new user" form uses Ajax to create a new user and then responds with this JS:

$("#disclosed_users_check_box_list").html("<%= escape_javascript(collection_check_boxes(:project, :disclosed_user_ids, User.order(:first_name, :last_name), :id, :name_with_job_title) { |b| "#{b.check_box} #{b.label}<br>" }).html_safe %>");  

The problem I am having is that the .html_safe at the end does not appear to be doing anything. When the response is rendered, I see the raw HTML appear on the "new project" page, instead of actual checkboxes and labels.

Any ideas of where I've gone wrong?

why does createElement prevent the DOM from loading in react-rails?

Posted: 07 May 2016 09:32 PM PDT

I'm going through this tutorial, and was fine until I changed the Records component and added React.createElement RecordForm, handleNewRecord: @addRecord between two DOM renderings. Seems to interfere and prevent the DOM from rendering at all.

Here's the component:

@Records = React.createClass    getInitialState: ->      records: @props.data    getDefaultProps: ->      records: []    addRecord: (record) ->      records = @state.records.slice()      records.push record      @setState records: records    render: ->      React.DOM.div        className: 'records'        React.DOM.h2          className: 'title'          'Records'        React.createElement RecordForm, handleNewRecord: @addRecord        React.DOM.hr null        React.DOM.table          className: 'table table-bordered'          React.DOM.thead null,            React.DOM.tr null,              React.DOM.th null, 'Date'              React.DOM.th null, 'Title'              React.DOM.th null, 'Amount'          React.DOM.tbody null,            for record in @state.records              React.createElement Record, key: record.id, record: record  

Console error says "Uncaught ReferenceError: RecordForm is not defined". Which, yes I do, and it's:

@RecordForm = React.createClass   bla bla bla bla     handleSubmit: (e) ->      e.preventDefault()      $.post '', { record: @state }, (data) =>        @props.handleNewRecord data        @setState @getInitialState()      , 'JSON'    render: ->      React.DOM.form       bla bla bla bla  

What gives?

Ruby on Rails Website [on hold]

Posted: 07 May 2016 08:38 PM PDT

I'm a noob programmer and I spent a while programming this but I can't figure out how to add it to my website. I made an app in Rails called talk and then I coded a sign-up type page which works on my http://localhost:3000/. I uploaded the entire folder onto my website with FileZilla FTP, but when I go to http://sonuforpres.com/talk it doesn't show up, 404.3 error, and my route made it work on http://localhost:3000/. As a fix, I attempted http://sonuforpres.com/talk/app/views/posts/index.html.erb. However, my fix didn't work. Any suggestions? BTW I have the Rails server running on my laptop right now.

Edit: I need to know how to run Ruby on Rails on a website.

why does button not render in react-rails?

Posted: 07 May 2016 09:32 PM PDT

Following this tutorial, and had everything working until the part where he brings in the submit button. Why won't the button render for me?

Here's my component:

@RecordForm = React.createClass    ...   render: ->    ...    React.DOM.button     type: 'submit'     className: 'btn btn-primary'     disabled: !@valid()     'Create record'  

Cannot start the server with gem acts_as_xlsx

Posted: 07 May 2016 07:36 PM PDT

I cannot start the server after adding the gem "acts as xlsx" to my gemfile.

I have read other posts on this problem but still haven't got a clue what is going on. Most seem to have resolved the problem by removing the gem from the gemfile but I need it to do what I want to do.

The error message is

"bin/rails:6: warning: already initialized constant APP_PATH /home/ubuntu/workspace/horsestud_app/bin/rails:6: warning: previous definition of APP_PATH was here  Error: Command '-b' not recognized"  

Thanking you in advance...

No comments:

Post a Comment