Saturday, April 2, 2016

Rails mapping data | Fixed issues

Rails mapping data | Fixed issues


Rails mapping data

Posted: 02 Apr 2016 07:51 AM PDT

I have Rails application with a database structured like this: database structure

The user selects some expertises and it's all saved as expected, same for the profiles, the profiles select some expertises and all is saved as expected. I can find profiles associated with expertise.

Now, let's say a user selects some expertises and I want to show all the profiles with the same expertises? Any ideas on how to do this?

Could this be done in the controller or would I need to create another join table?

Saving data to first model and using the generated key to save data to other model in Rails

Posted: 02 Apr 2016 07:32 AM PDT

I have a model named Product that belongs to two model namely User and Address.

class Product < ActiveRecord::Base      belongs_to :user      belongs_to :address      validates :title, :description, :user_id, :address_id presence: true      validates :product_type, numericality:{:greater_than => 0, :less_than_or_equal_to => 2}, presence: true  end  

Now the problem is that a user will enter the address at the time of filling up the product information so I do not have an address_id to feed to the Product model. How can I do this? One option is to first save the data in Address model and then use the generated id to feed in to the Product model. Is there any better way to do it?

use mailgun api and send email with javascript?

Posted: 02 Apr 2016 07:39 AM PDT

I am trying to use mailgun.com for sending emails. But it happened that I need to send it with js (cause sometimes I built websites with rubyonrails, sometimes with python. And now I need to built a simple landing page with mail sending. And hosting (which is free ad suits me only supports php which I don't know) So I decided to use js and obfuscate this code and paste it somewhere in somelibrary.So no one will ever find my secret key) Can someone help with translating some of this examples into js code?

This is python example:

def send_simple_message():      return requests.post(          "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",          auth=("api", "YOUR_API_KEY"),          data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",                "to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],                "subject": "Hello",                "text": "Testing some Mailgun awesomness!"})  

This is c# example

public static IRestResponse SendSimpleMessage() {         RestClient client = new RestClient();         client.BaseUrl = new Uri("https://api.mailgun.net/v3");         client.Authenticator =                 new HttpBasicAuthenticator("api",                                            "YOUR_API_KEY");         RestRequest request = new RestRequest();         request.AddParameter("domain",                              "YOUR_DOMAIN_NAME", ParameterType.UrlSegment);         request.Resource = "{domain}/messages";         request.AddParameter("from", "Excited User <mailgun@YOUR_DOMAIN_NAME>");         request.AddParameter("to", "bar@example.com");         request.AddParameter("to", "YOU@YOUR_DOMAIN_NAME");         request.AddParameter("subject", "Hello");         request.AddParameter("text", "Testing some Mailgun awesomness!");         request.Method = Method.POST;         return client.Execute(request);  }  

This is php example

# Include the Autoloader (see "Libraries" for install instructions)  require 'vendor/autoload.php';  use Mailgun\Mailgun;    # Instantiate the client.  $mgClient = new Mailgun('YOUR_API_KEY');  $domain = "YOUR_DOMAIN_NAME";    # Make the call to the client.  $result = $mgClient->sendMessage($domain, array(      'from'    => 'Excited User <mailgun@YOUR_DOMAIN_NAME>',      'to'      => 'Baz <YOU@YOUR_DOMAIN_NAME>',      'subject' => 'Hello',      'text'    => 'Testing some Mailgun awesomness!'  ));  

This is rails example:

def send_simple_message    RestClient.post "https://api:YOUR_API_KEY"\    "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",    :from => "Excited User <mailgun@YOUR_DOMAIN_NAME>",    :to => "bar@example.com, YOU@YOUR_DOMAIN_NAME",    :subject => "Hello",    :text => "Testing some Mailgun awesomness!"  end  

Imagemagick support for Ruby on Rails Windows

Posted: 02 Apr 2016 07:46 AM PDT

was trying to download Window Binary Release for ImageMagick installation in Windows 7 Rails 4.2.4, Ruby 2.1.5.

however all the download links returned 'not found'.

ImageMagick windows binary release link

Are there any alternative links to download the file so that a proper installation can be done?

Add table columns correctly in rails 4

Posted: 02 Apr 2016 07:24 AM PDT

I'm writing a simple rails app which has users,projects and tasks. And I have the next problem: each user must have his own projects,and each projects must have it's own tasks.When I'm trying to debug my app via console I can see that projects and tasks are created without "user_id" and "project_id".So my DB was configurated incorrectly and because of app doesn't work correctly(columns weren't add to Projects and Tasks tables and because of it app simply can't create projects,that will belong to only one user and tasks which belong to only one project.(and that's the main point of the app) Can someone help me to deal with my models and migrations,cause I'me really stuck with this stuff

Here are the corresponding models and migrations

Project.rb

class Project < ActiveRecord::Base    belongs_to :user    has_many :tasks, dependent: :destroy    validates :name, presence: true, uniqueness: true  end  

User.rb

class User < ActiveRecord::Base    has_many :tasks, through: :projects, dependent: :destroy    has_many :projects, dependent: :destroy    attr_accessor :remember_token    before_save { self.email = email.downcase }    validates :name,  presence: true, length: { maximum: 50 }    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i    validates :email, presence: true, length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }    has_secure_password    validates :password, presence: true, length: { minimum: 6 }, allow_nil: true      # Returns the hash digest of the given string.    def User.digest(string)      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :                                                    BCrypt::Engine.cost      BCrypt::Password.create(string, cost: cost)    end      # Returns a random token.    def User.new_token      SecureRandom.urlsafe_base64    end      # Remembers a user in the database for use in persistent sessions.    def remember      self.remember_token = User.new_token      update_attribute(:remember_digest, User.digest(remember_token))    end      # Returns true if the given token matches the digest.    def authenticated?(remember_token)      return false if remember_digest.nil?      BCrypt::Password.new(remember_digest).is_password?(remember_token)    end      # Forgets a user    def forget      update_attribute(:remember_digest, nil)    end  end  

Task.rb

class Task < ActiveRecord::Base    belongs_to :project  end  

Migration for creating projects

class CreateProjects < ActiveRecord::Migration    def change      create_table :projects do |t|        t.string :name          t.timestamps null: false      end    end  end  

And for creating tasks

class CreateTasks < ActiveRecord::Migration    def change      create_table :tasks do |t|        t.string :name        t.datetime :deadline          t.timestamps null: false      end    end  end  

Now when I try to create/update/delete a new task I always get some errors likeenter image description here

Also here are the corresponding controllers,maybe something also wrong there

projects_controller.rb

class ProjectsController < ApplicationController    before_action :find_project!, only: [ :update, :destroy]      # GET /projects    # GET /projects.json    def index      @projects = current_user.projects      @project  = Project.new    end      # GET /projects/1    # GET /projects/1.json    def show    end      # GET /projects/new    def new      @project = Project.new    end      # GET /projects/1/edit    def edit    end      # POST /projects    # POST /projects.json    def create      @project = current_user.projects.create(project_params)        respond_to do |format|        if @project.save          format.html { redirect_to home_url }          format.json { render :show, status: :created, location: @project }        else          format.html { render :home_url }          format.json { render json: @project.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /projects/1    # PATCH/PUT /projects/1.json    def update      respond_to do |format|        if @project.update(project_params)          format.html { redirect_to home_url }          format.json { render :show, status: :ok, location: @project }        else          format.html { render :home_url }          format.json { render json: @project.errors, status: :unprocessable_entity }        end      end    end      # DELETE /projects/1    # DELETE /projects/1.json    def destroy      @project.destroy      respond_to do |format|        format.html { redirect_to home_url }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions        def find_project!        @project = current_user.projects.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def project_params        params.require(:project).permit(:name)      end  end  

tasks_controller.rb

class TasksController < ApplicationController    before_action :set_task, only: [:show, :edit, :update, :destroy]      # GET /tasks    # GET /tasks.json    def index      @tasks = Task.all    end      # GET /tasks/1    # GET /tasks/1.json    def show    end      # GET /tasks/new    def new      @task = Task.new    end      # GET /tasks/1/edit    def edit    end      # POST /tasks    # POST /tasks.json    def create      @task = @project.tasks.create(task_params)        respond_to do |format|        if @task.save          format.html { redirect_to home_url }          format.json { render :show, status: :created, location: @task }        else          format.html { render :home_url }          format.json { render json: @task.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /tasks/1    # PATCH/PUT /tasks/1.json    def update      respond_to do |format|        if @task.update(task_params)          format.html { redirect_to home_url }          format.json { render :home_url, status: :ok, location: @task }        else          format.html { render :home_url }          format.json { render json: @task.errors, status: :unprocessable_entity }        end      end    end      # DELETE /tasks/1    # DELETE /tasks/1.json    def destroy      current_user.tasks.where(id: params[:task][:task_ids])      respond_to do |format|        format.html { redirect_to home_url }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def task_params        params.require(:task).permit(:name, :position)      end      def find_task!      @task = current_user.tasks.find(params[:id])    end      def find_project!      @project = current_user.projects.find(params[:task][:project_id])    end  end  

Migrate complex React SPA from CoffeeScript to ES2015 (advice, reasons, benefits)

Posted: 02 Apr 2016 06:54 AM PDT

I have a big SPA I developed 1.5 years ago. It is a React.js app written in CoffeeScript. It is hosted in Ruby on Rails with asset pipeline. On that moment I thought it was a good idea.

I used globally exposed object to access different parts of an app.

@App =    Components:      Layouts: {}      Pages: {}    Forms: {}    Actions: {}    Stores: {}    Models: {}    Collections: {}    Entities: {}    APIRoot: '/api/v1/'  

I also created a small decorator around React.DOM so I ended up using it directly without JSX compiler

react_dom.coffee

build_tag = (tag) ->    (options...) ->      options.unshift {} if options[0]['_isReactElement'] or options[0].constructor isnt Object      React.DOM[tag].apply @, options    @d = do ->    object = {}    for element in Object.keys(React.DOM)      object[element] = build_tag element    object  

It exposes global object d with all React.DOM elements so I was able to use Jade/Slim like syntax

d.section className: 'popular',     d.header className: 'page__header', 'Header text'     d.p className: 'block-placeholder', 'Some paragraph'  

Since then I worked a lot with ES2015 and I can clearly see benefits so I'm considering to move whole codebase to ES2015 and module syntax with babel.

The questions are:

  1. Is it a really good idea to port everything to ES2015? Can anyone share same experience?
  2. What is the best way to organise ES2015 module syntax with React.js and JSX in Rails app? (I looking into react_on_rails)
  3. Any other advices and thoughts on this topic would be appreciated.

Error Installing react-rails with Rails 5 beta.3

Posted: 02 Apr 2016 07:52 AM PDT

Running a newly installed Rails 5 beta 3 with Ruby 2.2.3. Added react-rails 1.6.0 in the gem file then bundle install.

Installed then rails s. Then error:

Users/sylar/.rvm/gems/ruby-2.2.3/bundler/gems/rails-442207387e62/railties/lib/rails/railtie/configuration.rb:95:in method_missing': undefined methodassets' for # (NoMethodError)

Is this a react-rails issue or rails 5 itself? Works ok in Rails 4.2.5.

Create a custom many-to-many association - Ruby on Rails

Posted: 02 Apr 2016 06:59 AM PDT

I'm trying to make an application to store played FIFA games.

I'm having some trouble setting up the right associations.

I have 2 models at this time, User and Game.

SCHEMA:

ActiveRecord::Schema.define(version: 20160402112419) do      create_table "games", force: :cascade do |t|      t.integer  "home_team_user_id"      t.integer  "away_team_user_id"      t.string   "home_score"      t.string   "away_score"      t.integer  "winner_id"      t.integer  "loser_id"      t.datetime "created_at",        null: false      t.datetime "updated_at",        null: false    end      create_table "games_users", id: false, force: :cascade do |t|      t.integer "user_id"      t.integer "game_id"    end      add_index "games_users", ["user_id", "game_id"], name: "index_games_users_on_user_id_and_game_id"      create_table "users", force: :cascade do |t|      t.string   "username"      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  

MODELS:

class Game < ActiveRecord::Base      has_and_belongs_to_many :users  end    class User < ActiveRecord::Base      has_and_belongs_to_many :games    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end  

As you can see the "Games" table has 2 corresponding ID's:

  • home_team_user_id
  • away_team_user_id

These will store the user_id from the Users table, this is needed to calculate who's the winner corresponding with the score.

Console results:

irb(main):001:0> Game.last    Game Load (0.0ms)  SELECT  "games".* FROM "games"  ORDER BY "games"."id" DESC LIMIT 1  => #<Game id: 1, home_team_user_id: 1, away_team_user_id: 1, home_score: "1", away_score: "2", winner_id: 1, loser_id: 1, created_at: "2016-04-02 12:27:26", updated_at: "2016-04-02 12:27:26">  irb(main):002:0> game = Game.find(1)    Game Load (0.5ms)  SELECT  "games".* FROM "games" WHERE "games"."id" = ? LIMIT 1  [["id", 1]]  => #<Game id: 1, home_team_user_id: 1, away_team_user_id: 1, home_score: "1", away_score: "2", winner_id: 1, loser_id: 1, created_at: "2016-04-02 12:27:26", updated_at: "2016-04-02 12:27:26">  irb(main):003:0> game.users    User Load (0.5ms)  SELECT "users".* FROM "users" INNER JOIN "games_users" ON "users"."id" = "games_users"."user_id" WHERE "games_users"."game_id" = ?  [["game_id", 1]]  => #<ActiveRecord::Associations::CollectionProxy []>  

I'm thinking now that the User.id needs to be linked to each individual corresponding id from the Games table.

How can I set this up? Do I need to use the has_many :through association?

Carrierwave - Presence validation triggering if filetype not on whitelist

Posted: 02 Apr 2016 06:00 AM PDT

In my rails 4 app I am using carrierwave to upload images.

class UserItemImage < ActiveRecord::Base      include PicturesHelper      attr_accessor :foo      mount_uploader :picture, PictureUploader    belongs_to :user_item    validate :picture_size    validates :picture, presence: true    end  

I am using this whitelist in my picture_uploader.rb

  def extension_white_list      %w(jpg jpeg png)    end  

My form

  <%= simple_form_for :user_item_image, url: user_item_user_item_images_path(@user_item), multipart: true do |f| %>      <%= f.input :picture, as: :file, label: false, input_html: {multiple: true, class: 'image-file'} %>  

When I try attaching a file with an extension not on the whitelist. I am getting a "can't be blank" error message. If I remove the presence validation, then the white_list validation error displays correctly. I really want the file extension error message to show up instead, because technically it's not blank it just has an incorrect file.

Docker + (rails and angular)

Posted: 02 Apr 2016 05:51 AM PDT

How can I use docker with a rails backend and an angular frontend to host multiple apps (staging, testing and production) on the same ec2 instance on AWS?

Architecture

  • My rails app serves the index.html file from where angular takes over
  • I am using passenger with unicorn to serve my app through Apache
  • I want to virtually host the same app for staging, testing and production

Should I even use docker for this?

Rails generate subsclass doesn't create new table

Posted: 02 Apr 2016 06:11 AM PDT

Here are the commands I use to generate rails models:

rails g scaffold fruit name variety colour  rails g scaffold vegetable harvested_at:time --parent Fruit   

The 2nd command was executed without error but it does not work, it only creates a model without the extra attribute, and there is no db migration generated either. Why is it so?

installing heroku with ruby on rails stucks...(windows 10)

Posted: 02 Apr 2016 04:43 AM PDT

Hello and thank you very much for your help (In advanced) I am using windows 10, and have installed ruby on rails and all the other components with rails installer while actuelly folowing the insrtuctions here:

http://installfest.railsbridge.org/installfest/create_a_heroku_account

while after installing toolbelt and trying to connect to heroku through the "heroku login" command the computer is basically... stuck...

this is how it looks:

C:\Sites>heroku login heroku-cli: Installing Toolbelt v4... done For more information on Toolbelt v4: https://github.com/heroku/heroku-cli heroku-cli: Adding dependencies... 12 MB/12 MB heroku-cli: Adding dependencies... 4.34 MB/4.34 MB heroku-cli: Installing core plugins...

What am i suppose to do now? (For the record i have tried uninstalling the toolbelt and after restrating the computer i have tried everything again).

Would it be better for me, under the sercumstances to try and use APTANA and connect heroku through it (i know this last question may seem a bit stupit to some of you - i an a real newbe to programming so i applogise for maybe asking such questions).

thank you again.

Historic table in Ruby on Rails

Posted: 02 Apr 2016 05:10 AM PDT

I'm new in Ruby On Rails, so, this is probably going to be a stupid question. I need to create a table to save the history of the transitions of an attribute. The problem is that transition it's in a diferent class from the one where I'm creating the table. It goes something like this:

class Family::Parent        class Historic         def add_historic           #code     end  end    class Family::Parent < ActiveRecord::Base          def make_transition            #code        end  end  

I know I can use something like ActiveModel::Dirty, but I have no idea how to do it, do you have any idea aout this ? Thank you!

Ember, hasMany and belongsTo doesn't work

Posted: 02 Apr 2016 06:37 AM PDT

I tried a simple emberapp to display some userdata.

My API returns me this json:

{     "roles":[        {           "id":5,           "name":"admin",           "alias":"Administrator",           "users":[              {                 "id":1,                 "username":"Evolutio",                 "email":"mail@evolutio.tld",                 "display_role":"Administrator"              }           ]        },        {           "id":2,           "name":"user",           "alias":"Benutzer",           "users":[             ]        },        {           "id":1,           "name":"banned",           "alias":"Gesperrt",           "users":[             ]        },        {           "id":3,           "name":"mod",           "alias":"Moderator",           "users":[             ]        },        {           "id":4,           "name":"support",           "alias":"Supporter",           "users":[             ]        }     ]  }  

my user/model.js:

import DS from 'ember-data';    export default DS.Model.extend({    username: DS.attr('string'),    email: DS.attr('string'),    display_role: DS.attr('string'),      roles: DS.belongsTo('role'),  });  

and my role/model.js

import DS from 'ember-data';    export default DS.Model.extend({    name: DS.attr('string'),    alias: DS.attr('string'),      users: DS.hasMany('user'),  });  

With this setup I got this error in my developer console:

Error while processing route: team.index Assertion Failed: Passing classes to store methods has been removed. Please pass a dasherized string instead of undefined EmberError@  

I didn't get the mistake. Maybe anyone can help me for this.

Rails 4.2 valid code or not?

Posted: 02 Apr 2016 04:27 AM PDT

i've got the following code

def self.activate_lessons  i = 0  #for lesson in Lesson.to_activate  for lesson in Lesson.find :all, :conditions => ["start_date < ? AND (active <> ? OR active IS NULL)", DateTime.now, true]    lesson.active = true    lesson.save    i += 1    end    i  end  

is this a vaild rails 4.2 code or not?

I got this error:

ActiveRecord::RecordNotFound: Couldn't find all Lessons with 'id': (all, {:conditions=>["start_date < ? AND (active <> ? OR active IS NULL)", Sat, 02 Apr 2016 09:50:06 +0000, true]}) (found 0 results, but was looking for 2)  

Bad ID to Mysql from Rails

Posted: 02 Apr 2016 02:36 AM PDT

I do something wrong and now rails put bad id value to table.

When app create profile it set for example id 2 but in mysql

id = 1  

Is there some way to fix it? I use devise gem if that helps

Ruby on Rails - how do I select which data I want to render from seed.rb file?

Posted: 02 Apr 2016 03:26 AM PDT

I have a seed.rb file in my rails app which contains 151 objects.

In my .html file I'm able to render ALL my objects in the seed.rb file.

  <tbody>      <% @pokemon.each do |pokemon| %>        <tr>          <td class="col-md-6">            <a href="/pokemon/<%=pokemon.no%>"><%= pokemon.name %></a>            <br>            <%= pokemon.no %>          </td>        </tr>      <% end %>    </tbody>  

How do I render ONE object or a specific object?

Here's an example of my seed data:

pokemon = Pokemon.create({ no: '001', name: 'Bulbasaur' })

pokemon = Pokemon.create({ no: '002', name: 'Ivysaur' })

pokemon = Pokemon.create({ no: '003', name: 'Venusayr' })

Ruby on Rails: Allow less than sign '<' inside code block with sanitize helper

Posted: 02 Apr 2016 06:12 AM PDT

I'm trying to escape user generated content in Rails. I have used raw with sanitize and raw helpers to filter content like this:

raw(sanitize(code, :tags =>   ['<', 'h2','h3','p','br','ul','ol','li','code','pre','a'] ))  

The list of tags mentioned are allowed in the content.

The problem is when I try to test it with a sql query like this:

mysql -u sat -p -h localhost database <  data.sql  

inside pre and code blocks it removes everything after the less than (<) sign.

Please help me figure out a way to do this.

Why is my rails controller passing different values to 2 partials rendered by the same action?

Posted: 02 Apr 2016 01:54 AM PDT

I have an app with SalesOpportunities - beneath these there are SaleQualifiers (which belong_to SalesOpportunity) which fit into 4 stages ("Need", "Budget", "Fit", "Negotiation"). I'm displaying these 4 stages as tabs on the SalesOpportunity show page, and when the user clicks a tab it will call a custom controller action to select the relevant SaleQualifiers to display in the pane beneath. So far this works well, but I'm trying to ensure the tab updates with the selected stage as the "active" tab - and this isn't working. The pane holds the right info, but the tabs are not correct:

SalesOpportunity show Controller action:

def show   @sales_opportunity = SalesOpportunity.find(params[:id])   session[:sales_opportunity_id] = @sales_opportunity.id   #set the SaleQualifier stages to show on the tabs   @stages = Question.order(:id).pluck(:sale_stage).uniq   @stage = @sales_opportunity.sale_status   @questions = Question.where(sale_stage: @stage)   #find any answered sale_qualifiers in this sale_stage   @sale_qualifiers = SaleQualifier.find_by_sql(["SELECT sale_qualifiers.* FROM sale_qualifiers INNER JOIN questions ON questions.id = sale_qualifiers.question_id WHERE sales_opportunity_id = ? AND questions.sale_stage = ? ", @sales_opportunity.id, @stage])   #find some unanswered sale_qualifiers and build them   @sale_qualifier = SaleQualifier.new(sales_opportunity_id: params[@sales_opportunity.id])    @answer = @sale_qualifier.build_answer   #find the right question to render and link to the sale_qualifier   @question = Question.find(@sales_opportunity.next_question)  end  

This action just ensures the right pane is set on first loading the SalesOpportunity show page.

Here's the custom action to find the right SaleQualifiers according to their actions:

def prospect_qualifiers   @sales_opportunity = SalesOpportunity.find_by(id: session[:sales_opportunity_id])   @stage = params[:sale_stage]   @questions = Question.where(sale_stage: @stage)   @stages = Question.order(:id).pluck(:sale_stage).uniq   @sale_qualifiers = SaleQualifier.find_by_sql(["SELECT sale_qualifiers.* FROM sale_qualifiers INNER JOIN questions ON questions.id = sale_qualifiers.question_id WHERE has_answer = 'true' AND sales_opportunity_id = ? AND questions.sale_stage = ? ", @sales_opportunity.id, @stage])   #when there's no sale_qualifiers from this sale_stage we can just select the first one according to the question and build that   if @sale_qualifiers.blank?    @question = Question.order(:id).where(sale_stage: @stage).first    @sale_qualifier = SaleQualifier.new(sales_opportunity_id: params[@sales_opportunity.id], question_id: @question.id)    @answer = @sale_qualifier.build_answer    render :modal_form   else    #when some of the sale_qualifiers of this sale_stage exist we'll need to be more specific about which question is next    @sale_qualifier = SaleQualifier.new(sales_opportunity_id: params[@sales_opportunity.id])    @answer = @sale_qualifier.build_answer    #find the right question to render and link to the sale_qualifier    @question = Question.find(@sales_opportunity.next_question)    render :modal_form   end  end  

This takes the sale_stage as a parameter passed from the link to this action, and uses that to find the right SaleQualifiers.

The offending part of my view code is below:

<div  id="qualifier-tabs">    <ul class="nav nav-tabs">      <%= render partial: 'shared/tabs', collection: @stages, as: :stage %>    </ul>  </div>  <div class="tab-content", id="qualifier_panel">    <%= render partial: 'shared/panel', collection: @stages, as: :stage %>   </div>  </div>  

shared/tabs partial:

<% if stage == @stage %>   <li class="active"><%= link_to stage, prospect_qualifiers_sale_qualifiers_path(:sale_stage => stage), :remote => true, data: { disable_with: "Loading...", toggle: 'tab' } %></li>  <% else %>   <li><%= link_to stage, prospect_qualifiers_sale_qualifiers_path(:sale_stage => stage), :remote => true, data: { disable_with: "Loading...", toggle: 'tab' } %></li>  <% end %>  

As you can see this compares the collection: @stages as: stage to the @stage variable passed from the controller action, determining whether they match - if so we make that the active tab.

The shared/panel partial:

<% if stage ==  @stage %>   <div class="tab-pane active" id='<%=stage %>'>      <table class="table table-striped display responsive no-wrap">               <thead>                <tr>                   <th>Question</th>                   <th>Answer</th>                   <th>Action</th>                </tr>               </thead>               <tbody>               <!-- if a sale_qualifier exists with an answer show the following -->                <% @sale_qualifiers.each do |qual| %>                <tr>                  <td><%= qual.question.question_text %></td>                  <% if qual.question.answer_type == "Datetime"%>                      <td><%= qual.answer.answer_text.to_date.readable_inspect %></td>                  <% elsif qual.question.answer_type == "Boolean" %>                      <% if qual.answer.answer_text == 'true'%>                          <td>Yes</td>                      <% elsif qual.answer.answer_text == 'false' %>                          <td>No</td>                      <% end %>                  <% else %>                      <td><%= qual.answer.answer_text %></td>                  <% end %>                  <td><%= link_to('edit', edit_sale_qualifier_path(qual), class: "btn btn-sm btn-warning", data: { disable_with: "Loading...", dismiss: 'modal' }, :remote => true )%></td>                </tr>                <% end %>                <!-- if there's no sale_qualifier with the question id then build one -->                  <%= form_tag('/sale_qualifiers', :id => 'new_sale_qualifier', :class => 'form', method: :post, remote: true, data: { model: "sale_qualifier" }) do -%>                      <%= fields_for :sale_qualifier do |ff| %>                          <%= ff.hidden_field :sales_opportunity_id, :value => @sales_opportunity.id %>                          <%= ff.hidden_field :question_id, :value => @question.id %>                        <tr>                          <td><%= @question.question_text %></td>                          <td>                            <%= ff.fields_for :answer_attributes do |answer| %>                                <div class="form-group">                                <% if @question.answer_type == 'Text Field' %>                                  <%= answer.text_area :answer_text, :placeholder => "Enter your answer"%>                                <% end %>                                <% if @question.answer_type == 'Datetime' %>                                  <div class='input-group date' id='datetimepicker' data-date-format="YY.MM.DD">                                    <%= answer.text_field :answer_text, class: "form-control", data: { date_format: 'YYYY/MM/DD' }, :placeholder => "YYYY/MM/DD" %>                                    <span class="input-group-addon">                                      <span class="glyphicon glyphicon-calendar"></span>                                     </span>                                  </div>                                <% end %>                                <% if @question.answer_type == 'Boolean' %>                                  <%= answer.select :answer_text, [['Yes', true], ['No', false]] %>                                <% end %>                                <span class="warning-block"></span>                                <span class="help-block"></span>                               </div>                            <% end %>                          </td>                          <td>                              <%= submit_tag "Submit", class: "btn btn-large btn-success", id: "sale_qualifier_submit", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>                          </td>                       </tr>                      <% end %>                       <% end %>                 </tbody>          </table>   </div>  <% else %>   <div class="tab-pane" id='<%=stage %>'>   </div>  <% end %>  

The pane does the same equivalence test and decides how to show the SaleQualifiers.

Here's the modal_form code:

$('#qualifier_tabs').html("<%= j render :partial => 'shared/tabs', collection: @stages, as: :stage %>");  $('#qualifier_panel').html("<%= j render :partial => 'shared/panel', collection: @stages, as: :stage %>");  

The problem is that the pane shows the right SaleQualifiers but the active tab remains on "Need". If I put in <%= @stage %> and <%= stage %> outputs into the tab partial and also into the panel partial I get the reason - the tab panel always shows "Need" "Need" as the output from those erb snippets, whereas the pane panel shows whatever sale_stage is actually coming from my prospect_qualifiers action.

How can the prospect_qualifiers action (which calls the modal_form file and therefore renders both partials into the view) be passing different values for @stage and stage to these two partials when they're being rendered by the same controller action?

Faye doesn't work properly

Posted: 02 Apr 2016 06:07 AM PDT

I'm writing a simple real-time chat, so I decided to use web-sockets. I used gem 'faye-rails'. Web console shows that it works POST http://khersonchat.herokuapp.com/faye [HTTP/1.1 200 OK 170ms] but when I send a message there's an error: While loading the page connection ws://khersonchat.herokuapp.com/faye was broken(translated from Russian). So when I send a message, the whole page still reloads, and I need to reload a page to see other people's messages sent.

messages_controller.rb:

def create      respond_to do |format|          if current_user              @message = current_user.messages.build(message_params)              if @message.save                  flash[:success] = 'Message sent'              else                  flash[:error] = 'Oops, an error :('              end              format.html {redirect_to root_path}              format.js          else              format.html {redirect_to root_path}              format.js {render nothing: true}          end      end  end  

application.js:

//= require jquery  //= require jquery_ujs  //= require faye  //= require messages  //= require_self  //= require turbolinks  

messages.coffee:

window.client = new Faye.Client('/faye')    jQuery ->      $('#new_message').submit ->          $(this).find("input[type='submit']").val('Sending...').prop('disabled', true)      try          client.unsubscribe('/messages')      catch          console?.log "Can't unsubscribe"        client.subscribe '/messages', (payload) ->          $('#messages').find('.media-list').append(payload.message) if payload.message  

create.js.erb

publisher = client.publish('/messages', {      message: '<%= j render @message %>'  });    publisher.callback(function() {       $("#message_body").val('');       $("#new_message").find("input[type='submit']").val('Send').prop('disabled', false)  });    publisher.errback(function() {      alert('Oops, an error');  });  

https://github.com/AlexNikolaev94/chatclone.git - up-to-date source code

important! the chat authenticates via omniauth, using a social network Vkontakte(vk.com), so the version stored in git has the access to localhost

Creating and displaying statistics of model data? (ruby on rails)

Posted: 02 Apr 2016 01:31 AM PDT

I've been struggling with finding a path to understanding how to create a real time graph based on a model in my rails database. I've seen examples of gruff, flot. I also was reading a few old articles that used fnordmetric. My problem still persists.

I'm looking to be able to display a page that has analytics and stats about that model .

for example a tshirt model- within the page I would like provide a graph of the # of sales that shirt did within a month's time to a user . and also display the total amount of money that model has sold. I have a pretty good idea on how to create the methods that'll handle those calculations but I'm lost on where to even start. Through the different gems and plugins the only thing I'm sort of understanding is just how to make standards graphs. Where I want the statistics page to be able to update in real time.

The only thing I've found that has gotten closest to what I'm looking for is https://github.com/jhund/rails-data-explorer. But it also lacks information .

If anyone can maybe point me in the right direction or is it some time of learning path to grasp the concept of creating analytics and integrating graphs into ruby on rails. Any help would be amazingly appreciated.

work around rails table naming conventions

Posted: 02 Apr 2016 02:08 AM PDT

I'd like to make friends rails with system with another database naming conventions. Is there possible to work around rails naming conventions? At least database table naming. It would be desirable to key name be just add '_id' suffix to table name. For example result join condition wanted like this 'parent'.'id' = 'child'.'parent_id'. If solution exists what is the invisible underwater rocks of solution?

Rails fonts were not precompiled for production

Posted: 02 Apr 2016 01:47 AM PDT

I've got some fonts added in the app/assets/fonts

they do not precompile for production ...

tried this in application.rb

module app     class Application < Rails::Application          config.assets.paths << Rails.root.join("app", "assets", "fonts", "tinymce")  

whats going wrong?

I'm Using rails 4.2

Different CSS files for different Layouts how to precompile?

Posted: 02 Apr 2016 01:46 AM PDT

I want different CSS files for different Layouts.

For example:

app/layouts/application.html.erb would have application.css

<%= stylesheet_link_tag 'application' %>  

and app/layouts/admin.html.erb will have admin.css:

<%= stylesheet_link_tag 'admin' %>  

Problem is that the admin.css is not precompiled when I run:

RAILS_ENV=production bundle exec rake assets:precompile  

What can I do that the admin.css is also precompiled?

I'm using Rails 4.2

EDIT

admin.css file

/*  //= require bootstrap.min  //= require filechooser  //= require bootstrap-switch.min  //= require jquery.datetimepicker  //= require fancybox2_1_5/jquery.fancybox  //= require blubb  *= require_self  

But onlye the code of the blubb.css file is added in admin.css ....

Resolve full view path to avoid duplicate rendering of modals

Posted: 02 Apr 2016 06:12 AM PDT

I need to render several bootstrap modals in my app. They are all contained in specific view files (possibly a cell or a normal view).

I may need to render a modal at very different places of my code (layout, view, cell, etc.) yet the modals must all be rendered at the same place in the HTML. So, I have introduced a helper load_modal(path, locals={}) that should be responsible for keeping track of all the modals that must be rendered. Another function is called somewhere in in my layout to render all the modals, near the end of layouts/application.html.erb.

I need to avoid loading several times the same modal, so I was thinking of raising an exception if the function is called several times with the same modal.

But : when calling the function, often I won't specify the full path to the file/view, but only the relative path

Example :

# app/views/posts/show.html.erb  ...  load_modal('comment_modal', post: @post)  # comment_modal means 'app/views/posts/_comment_modal.html.erb'  ...  

How do I get the full path to 'app/views/posts/_comment_modal.html.erb' from 'comment_modal' ?

Rails 4 - dynamic background image

Posted: 02 Apr 2016 01:28 AM PDT

I'm trying to make a rails 4 app, using a dynamic background image.

I've read several posts on SO that say it's best not to defined the object in the css file because it doesnt cache. I've tried to define it in my show page as follows - however nothing renders.

<div class="col-md-5 col-lg-4 vc-photo" style= 'background-image: url(<%= image_url @profile.user.avatar.profile.path if @profile.user.avatar? %>);' }>&nbsp;</div>  

I have also tried (swapping path for url):

<div class="col-md-5 col-lg-4 vc-photo" style= 'background-image: url(<%= image_url @profile.user.avatar.profile.url if @profile.user.avatar? %>);' }>&nbsp;</div>  

When I try inspecting the element in the code inspector, I can see:

<div class="col-md-5 col-lg-4 vc-photo" style="background-image: url();" }="">&nbsp;</div>  

Does anyone see what I've done wrong?

Inheriting from custom classes within models in rails

Posted: 02 Apr 2016 01:32 AM PDT

Just curious on how things autoloading works in rails

app/models/base_facebook_object.rb    class BaseFacebookObject  end  

In the file where I require it,

app/models/fb_campaign.rb    class FbCampaign < BaseFacebookObject  end  

But the above doesn't work as it says BaseFacebookObject not defined?

Do I always have to require the base object file in such cases?

require "#{Rails.root}/app/models/base_facebook_object"  

Thanks in advance

Need a range with all unicode characters

Posted: 02 Apr 2016 07:45 AM PDT

Classical Ruby implementation allows to iterate over the unicode characters:

('a'..'z').to_a   # ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]  ('@'..'[').to_a   # ["@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "["]  

I need to get an array with all the unicode characters (different locales, punctuation marks, etc). How do I do that? I don't know the very first and the last characters.

Get live updated data with ajax in a react component

Posted: 02 Apr 2016 01:21 AM PDT

Story:

User clicks "add", it sets a value in the database to true. Clicks "remove", updates same column to false in the database:

def add    u = User.find(1)    u.foo = true    u.save    u.reload    head :ok  end    def remove    u = User.find(1)    u.foo = false    u.save    u.reload    head :ok  end  

React button component:

...    _add(){    $.ajax({      url: ''url-to-the-controller-action-(add),      type: 'POST',      success: function (data) {          console.log("DB is set to: " this.props.uid)      },      error: function (data) {          console.log("not added")      }    });  },    _remove(){    $.ajax({      url: ''url-to-the-controller-action-(remove),      type: 'POST',      success: function (data) {          console.log("DB is set to: " this.props.uid)       },      error: function (data) {          console.log("not removed")      }    });  },    render(){    return(      <div>        <button onClick={this._add}>add</button>        <button onClick={this._remove}>remove</button>      </div>    )  }    ...  

My button receives props from another component:

Foo component

getInitialState: function() {    return{      uid: this.props.data,      }  }  

Foo's render:

<Button uid={this.state.uid} />  

I am sure I can achieve this without the need for flux/redux as that would be an over kill for this tiny component. I have looked into this but not sure how to use it.

The app works but I have to refresh the page to see the changes.

Or, Rails 5 is my best option with action cable?

Why I get user and not users on users/index route?

Posted: 02 Apr 2016 01:42 AM PDT

I tried to make a simple emberapp with rails, that shows some users info from our system.

My route: /api/users returns this json:

{"users":[{"id":1,"username":"Evolutio","email":"mail@evolutio.tld"}]}  

My emberadapter:

import DS from 'ember-data';  export default DS.RESTAdapter.extend({      host: 'https://api.domain.tld',      namespace: 'api',      headers: {          //"API_KEY": "secret key",      }  });  

my users/model.js

import DS from 'ember-data';    export default DS.Model.extend({    username: DS.attr('string'),    email: DS.attr('string')  });  

my users/index/route.js

import Ember from 'ember';    export default Ember.Route.extend({      model() {          let users = this.store.findAll("users");          return users;      }  });  

I visit this url: localhost:4200/users

When I delete the user/model.js I get this error:

WARNING: Encountered "users" in payload, but no model was found for model name "user" (resolved model name using frontend@serializer:application:.modelNameFromPayloadKey("users"))  

and the data with the ember inspector: enter image description here

my index template from users:

<ul>  {{#each model as |user|}}      <li>          {{#link-to 'users.show' user}}              {{user.username}} {{user.roles}}          {{/link-to}}      </li>  {{/each}}  </ul>  

my scnd problem is, that I cant make any relation. my api returns now this:

{"users":[{"id":1,"username":"Evolutio","email":"mail@evolutio.sh","roles":[{"id":5,"name":"admin","alias":"Administrator"}]}]}  

my user/model.js:

import DS from 'ember-data';    export default DS.Model.extend({    username: DS.attr('string'),    email: DS.attr('string'),      roles: DS.hasMany('role'),  });  

and now I got this error:

Error while processing route: users.index Assertion Failed: Passing classes to store methods has been removed. Please pass a dasherized string instead of undefined  

I solved it with this: my user_serializer.rb:

class UserSerializer < ActiveModel::Serializer    attributes :id, :username, :email, :display_role    #has_many :roles      def display_role      "#{object.roles[0].alias}"    end  end  

and my user/model.js:

import DS from 'ember-data';    export default DS.Model.extend({    username: DS.attr('string'),    email: DS.attr('string'),    display_role: DS.attr('string')  });  

No comments:

Post a Comment