Monday, September 5, 2016

Rails - show facebook post after admin acceeptation | Fixed issues

Rails - show facebook post after admin acceeptation | Fixed issues


Rails - show facebook post after admin acceeptation

Posted: 05 Sep 2016 07:43 AM PDT

I want to put facebook posts from my facebook page on my rails website, but they will be shown on the www after admin acceptation. I thought about creating table in mysql with facebook posts (link to post, visible) so the admin could change the 'visible' field to true/false. Will Koala gem help me with it? And facebook graph api? Maybe should I try it different way? Any ideas and tips will be very helpful

Performance wise will iOS extension files help in rendering big assets faster ?

Posted: 05 Sep 2016 07:42 AM PDT

We have a mobile app that builds its UI , partly via large video / animation files. Today we apply calls to our server to retrieve these assets . The problem is that the app's graphics is loading instantly aside for these assets that are loading ...

We are thinking of moving these large assets from where they are today ( on our servers ) to be part of the extension files ( up to 4 GB ) that appstore / google play offer. Question is : from your experience, will this change help render these big assets faster to the client?

Thanks

rails filter each method on results page

Posted: 05 Sep 2016 07:42 AM PDT

So i have this filter on the results page of my application

<div class="panel panel-default" style="margin-top: 10px">      <div class="panel-heading" style="color: #fff; background-color: #1292fd; font-weight:bold">Search Filters</div>      <div class="panel-body" style="color: #1292fd; font-weight:bold">        <label for="datefrom">Date From:</label>        <input type="date" id="datefrom" class="form-control" name="date" value="dd/mm/yyyy">        <label for="dateto">Date To:</label>        <input type="date" id="dateto" class="form-control" name="date" value="dd/mm/yyyy">        <hr>        <div style="float:right">          <button class="btn btn-info" name="button">Apply Filters</button>        </div>      </div>    </div>  

Just a simple date from to filter.

What i'm wanting to do is have the results in the each method which is above it filtered between the two dates selected. i'm under the impression i would need something like this:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)  

My controller looks like this at the moment:

  def search      @events = Event.page(params[:page]).per(10).search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)      if @events.results.any?        render 'events/results'      else        render 'events/noresults'      end    end  

So at the moment im unaware how to get the results to filter with the filter option.

any help is appreciated

Sam

Unique constraint issue paranoia gem

Posted: 05 Sep 2016 07:15 AM PDT

I have a rails app in which i am using devise and paranoia gems.
I have a users table in postgres db which has unique validation on email column. I am using paranoia for soft delete, issue is when i delete a user and then tey to create a user using the email of the deleted user it throws an error PG::UniqueViolation: ERROR.
I have read about this and know that this could be solved using partial index feature of rails.

http://scottsmerchek.com/2015/08/03/taking-the-d-out-of-crud/

https://devcenter.heroku.com/articles/postgresql-indexes#partial-indexes

How do i implement this?
Sorry for bad formatting, typing from mobile.

Error localhost:3000 - Errno::ECONNREFUSED at /courses

Posted: 05 Sep 2016 07:00 AM PDT

So I'm trying to preview a page with courses and I get this error: enter image description here

Connection refused - {:data=>"fq=type%3ACourse&fq=hidden_b%3Afalse&sort=university_sponsor_b+desc%2C+university_partner_b+desc%2C+score+desc%2C+score+desc%2C+name_s+asc&start=0&rows=15&q=%2A%3A%2A", :method=>:post, :params=>{:wt=>:ruby}, :query=>"wt=ruby", :headers=>{"Content-Type"=>"application/x-www-form-urlencoded; charset=UTF-8"}, :path=>"select", :uri=>#http://localhost:8982/solr/development/select?wt=ruby>, :open_timeout=>nil, :read_timeout=>nil, :retry_503=>nil, :retry_after_limit=>nil}

Using Statesman with Racsack to return particular states from dropdown

Posted: 05 Sep 2016 06:39 AM PDT

How do I use Ransack (with a dropdown menu of the states from Statesman) to return a subset of data from my collection?

Example;

Here is my dropdown;

<select class="select" name="q[state_machine_current_state_eq]" id="q_state_machine_current_state_eq">      <option selected="selected" value="pending">pending</option>      <option value="active">active</option>  </select>  

A record can either be "pending" or "active".

Here is my controller index method;

def index    @filter = current_sponsor      .card_holders      .ransack(params[:q])    @sponsor_card_holders = @filter      .result      .page(params[:page])      .per(3)      .decorate  end  

If I do a binding.pry now I can get this for @filter;

Ransack::Search<class: User::CardHolder, base: Grouping <combinator: and>>  

For @sponsor_card_holders.first.current_state

"active"  

For params[:q]

<ActionController::Parameters {"state_machine_current_state_eq"=>"active"} permitted: false>  

I think my issue is almost certainly the state_machine_current_state_eq part in my dropdown html. I've basically made an educated guess. I also tried current_state_eq.

I am expecting it to return something like;

Ransack::Search<class: User::CaseWorker, base: Grouping <conditions: [Condition <attributes: ["card_holder_state_machine"], predicate: eq, values: ["active"]>]>  

But it's ignoring the dropdown. What is the correct syntax?

Ruby on Rail app with Cloud9 and Postgres

Posted: 05 Sep 2016 06:46 AM PDT

I have a simple application on "Ruby on Rails" with "Active admin-gem" for the users authentification, I am trying to create a PostgreSQL database on C9, I have seen many tutorials but none works for me

So I have so far: Installation postgres gem - gem 'pg' Start the Postgresql on C9 Create database with name "mydatabase" Generate the user 'ubuntu' password 'ubuntu' Ubuntu is the owner of "mydatabase" Configuration of "database.yml"

My database.yml now, but i tried with others:

default: &default  adapter: postgresql  encoding: unicode  host: localhost  pool: 5  database: mydatabase  username: ubuntu  password: ubuntu    development:  <<: *default    test:  <<: *default    production:  <<: *default  

Error when i use: $ rake db:create

DEPRECATION WARNING: Passing a string to ActiveRecord::Base.establish_connection for a configuration lookup is deprecated, please pass a symbol (:postgresql) instead. (called from mon_synchronize at /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/monitor.rb:214)  rake aborted!  ActiveRecord::AdapterNotSpecified: 'postgresql' database is not configured. Available: ["default", "adapter", "encoding", "host", "pool", "database", "username", "password", "development", "<<", "test", "production"]  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:248:in `resolve_symbol_connection'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:231:in `resolve_string_connection'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:213:in `resolve_connection'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:139:in `resolve'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:151:in `block in resolve_all'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:150:in `each'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:150:in `resolve_all'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_handling.rb:69:in `resolve'  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/core.rb:46:in `configurations='  /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/railties/databases.rake:5:in `block (2 levels) in <top (required)>'  /usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'  Tasks: TOP => db:create => db:load_config  (See full trace by running task with --trace)  

im using this page: https://github.com/JohnnyBurst/c9_sqlite3_to_pg

appreciate any help.

Ruby on Rails crontab task is scheduled but not running

Posted: 05 Sep 2016 07:22 AM PDT

I am using the whenever gem to create the rake task, i am expecting to get a line output "Teaching Thabo how to schedule tasks" on my terminal every 2 minutes, i am new to Rails, here is the code for my rake task file which i have named request_invoice.rake

 namespace :request_invoice do    desc "Teaching Thabo how to schedule tasks"    task test_tasking: :environment do    puts "Learning the tasking in rails..."    end   end  

And the whenever gem created a schedule.rb file in the config of my project, i have the following code in the file

 every 2.minutes do   rake 'request_invoice:test_tasking'   end  

I have ran the whenever command on the terminal, it gives the following:

    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,5 2,54,56,58 /bin/bash -l -c 'cd /home/sable/GMS/grading-     management-solution && RAILS_ENV=production bundle exec rake    request_invoice:test_tasking --silent'  ## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated.  ## [message] Run `whenever --help' for more options.  

What data type use for taxrate field

Posted: 05 Sep 2016 06:28 AM PDT

What data type should I use for tax rate field in my RoR application. I want it to store only numbers from 0 to 100 and two fixed strings "zw" and "np". Should I use string type and parse it to integer when it's number?

syntax error, unexpected tIDENTIFIER, expecting keyword_end before_action :authenticate_user! except: [:index, :show] ^

Posted: 05 Sep 2016 06:32 AM PDT

please i have been trying to connect to my local host and it gives me that @title. This is my code below: The red line indicates the line 3 authenticate. What could b the problem

class MoviesController < ApplicationController    before_action :set_movie, only: [:show, :edit, :update, :destroy]    before_action :authenticate_user! except: [:index, :show]  

Multiple selected data doesn't appear

Posted: 05 Sep 2016 06:17 AM PDT

I use select2 for multiple select. My problem is, I can select multiple value from json data and I can save this data in related model columns. But when I want to update this model, the selected data doesn't appear.

some part of my json data:

{   - categories:[     - {         id:7,         name:"Eğitim Bilimleri Enstitüsü"       },     - {         id: 8,         name: "Eğitim Yönetim Teftişi ve Planlaması 1. Yarıyıl"       },     ...    ]  }  

I have a Moodle class(it is not inheritance from ActiveRecord, just a class and it has some functions which return json data). I wonder whether it is right approach.

in the content of my form:

<%= simple_form_for(@period) do |f| %>  ...      <%= f.input :moodle_connect_ids, collection: Moodle.categories.map {|p| [ p['name'], p['id'] ] }, input_html: {multiple: true} %>  ...  <% end %>  

I explicitly set moodle_connect_ids to be an array in my controller:

params.require(:period).permit(..., :moodle_connect_ids => [])  

in the content of my .js file:

$("#period_moodle_connect_ids").select2({    placeholder: "Moodle Dönem Bağlantılarını Seçiniz",    multiple: true,    allowClear: true  });  

When I select to multiple values and save my model, the column's value looks like this:

> Period.last  => #<Period:0x007fcf53a4d830  id: 25,  ...  moodle_connect_ids: "[\"\", \"85\", \"120\"]"   ...  

Am I on the wrong way? Have you any suggestion?

Rails 5 , render a form without specific input

Posted: 05 Sep 2016 05:49 AM PDT

I am trying to render a partial form for editing but i don't want a specific part of that form to show up in the edit action. I am using the normal format render.

<%= render 'form', link: @link %>  

and i don't want to show a specific division

<div class="form-group">  <%= f.label :Description %><br>  <%= f.text_area :description, class: "form-control" %>  

Thank you,

RoR - The record failed to save when after its foreign key was set to nil

Posted: 05 Sep 2016 06:26 AM PDT

I'm trying to solve this problem of mine. I'll tell you what I did, where I struggle and hopefully you can lend me a hand. I'm kinda new to this Rails thing and get hopefully 1-2 good tips regarding my problem. That would be really awesome.

Problem:

LocationsController request to edit should load the requested location  Failure/Error: @location.image = @image       ActiveRecord::RecordNotSaved:         Failed to remove the existing associated image.   The record failed to save when after its foreign key was set to nil.    LocationsController request to edit should be successfull  Failure/Error: @location.image = @image       ActiveRecord::RecordNotSaved:         Failed to remove the existing associated image.   The record failed to save when after its foreign key was set to nil.  

Part of the Controller:

def new   @location = Location.new  end    def create    @location = Location.new(params[:location])    @location.owner_id = current_user.id    @address = Address.new(params[:address])    @location.image = Image.new(params[:image])    responds_to_parent do      if @location.save && @location.image.update_from_uploaded_data(params[:image])        @address.addressable = @location        @address.save        @locations = Location.all_as_select_options        respond_to do |format|          format.js { render layout: false }        end      else        render :update      end    end  end    def edit    @address = @location.address  end    def update    @location.image ||= Image.new    @location.address ||= Address.new    address = params[:address]      if @location.update_attributes(params[:location]) &&   @location.address.update_attributes(address) && @location.image.update_from_uploaded_data(params[:image])      flash[:notice] = 'Daten für den Ort wurden geändert.'      redirect_to location_path(@location)    else      flash[:notice] = 'Die Daten konnten nicht gespeichert werden'      render action: 'edit'    end  end    def destroy    @location.destroy if @location.owner.id == current_user.id    redirect_to action: 'index', controller: 'locations'  end    private    def load_location    @location = Location.find(params[:id])  end  

Rspec:

describe 'request to edit' do        before do          login(mock_admin)          @location = create_location          @image = create_image          Location.stub!(:find).and_return(@location)          Image.stub!(:find).and_return(@image)          @location.image = @image          get :edit, id: @location.id        end        it 'should be successfull' do          response.should be_success        end        it 'should load the requested location' do          assigns(:location).should eql(@location)        end        it 'should load the locations address' do          assigns(:address).should eql(@location.address)        end      end  

My attempt: Allowing parameters like location and image in my edit method. Like it was suggested at Can't update my nested model form for has_one association

I tried the

'params.require(:...).permit(...)'  

and

accepts_nested_attributes_for(:..., update_only: true)  

solution which were suggested. But even with all parameters allowing it didn't work out. Do you know why though? I tried to modify the methods but o well...

Edit -- -- Model:

class Location < ApplicationRecord    belongs_to  :owner, class_name: '::User', foreign_key: 'owner_id'    has_one     :address, as: :addressable, :dependent => :destroy    has_one     :image, as: :visualisable    has_many    :events      validates_presence_of :owner_id, :name      def display_name      [name.to_s, address&.display].compact.join(', ')    end      def self.all_as_select_options      all.collect { |m| [m.name, m.id] }    end      def can_be_deleted_by?(user)      owner == user && events.count == 0    end  end  

Routing Error uninitialized constant SubmitsController (Trying to upload document using Carrierwave)

Posted: 05 Sep 2016 06:01 AM PDT

I am building my first useful Rails application for a teacher to post assignments and students to upload their work (jpeg|pdf) on the website using Carrierwave.

Tutorial I want to replicate: http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm

Error: "`undefined method submits_path' for #<#:0x007f7260dbc7a0> Did you mean? submit_path"

Error message: Extracted source (around line #14):

13    <div class = "well">  14       <%= form_for @submits, html: { multipart: true } do |f| %>  15          <%= f.label :name %>  16          <%= f.text_field :name %>  17          <%= f.label :attachment %>  

model: submit.rb

class Submit < ActiveRecord::Base      mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.     validates :name, presence: true # Make sure the owner's name is present.  end  

controller: submit_controller.rb

class SubmitController < ApplicationController   def index        @submits = Submit.all   end       def new        @submit = Submit.new     end       def create        @submit = Submit.new(submit_params)          if @submit.save           redirect_to submits_path, notice: "The assignment #{@submit.name} has been uploaded."        else           render "new"        end       end       def destroy        @submit = Submit.find(params[:id])        @submit.destroy        redirect_to submits_path, notice:  "The assignment #{@submit.name} has been deleted."     end       private        def submit_params        params.require(:submit).permit(:name, :attachment)        end    end  

routes:

Rails.application.routes.draw do    resources :submit, only: [:index, :new, :create, :destroy]      get 'welcome/index'      get 'welcome/about'      root 'welcome#index'  end  

schema:

ActiveRecord::Schema.define(version: 20160903040246) do      create_table "submits", force: :cascade do |t|      t.string   "name"      t.string   "attachment"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end  

rake routes :

       Prefix Verb   URI Pattern              Controller#Action   submit_index GET    /submit(.:format)        submit#index                POST   /submit(.:format)        submit#create     new_submit GET    /submit/new(.:format)    submit#new         submit DELETE /submit/:id(.:format)    submit#destroy  welcome_index GET    /welcome/index(.:format) welcome#index  welcome_about GET    /welcome/about(.:format) welcome#about           root GET    /                        welcome#index  

Thanks in advance to all the wonderful people here who are willing to lend a helping hand

Rails 4 cascade save association with validation on belongs_to

Posted: 05 Sep 2016 05:41 AM PDT

I'm having troubles autosaving objects which are created this way. Consider having following models:

class SearchTerm < ActiveRecord::Base     has_many :search_term_occurrences, dependent: :destroy  end    class SearchTermOccurrence < ActiveRecord::Base     belongs_to :search_term     validates :search_term, presence: true # Problematic validation  end  

So when I try to do the following:

term = SearchTerm.new term: 'something'  term.search_term_occurrences << [SearchTermOccurrence.new, SearchTermOccurrence.new]  term.save!  

I get the following:

ActiveRecord::RecordInvalid: Validation failed: Search term occurrences is invalid, Search term occurrences is invalid  

But when I omit the validation on belongs_to search_term. Everything is saved properly.

My question is: How to save parent object and its association (newly created) whilst having validations on child objects without saving associated objects one by one and then saving parent object within transaction? I want Rails to handle the transactional logic.

Rails simple-form association not saving

Posted: 05 Sep 2016 06:26 AM PDT

Am new to RoR and Simple_form. I have a simple set-up where I have an association between 2 classes. The form I use is not updating/saving and always setting the value back to blank. Looked at the docs and other postings, what am I doing wrong?

Classes

class Annotation < ApplicationRecord  has_many :comments, dependent: :destroy  belongs_to :documenttype  has_attached_file :file, styles: { large: "600x600>", medium: "500x500>", thumb: "150x150#" }, default_url: "/images/:style/missing.png"    accepts_nested_attributes_for :documenttype    validates_attachment_content_type :file, content_type: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']  validates :name, presence: true, uniqueness: true, length: { minimum: 10, maximum: 50 }      validates :description, length: { minimum: 20, maximum: 500 }      validates :documenttype, presence: true      validates :file, presence: true    end    class Documenttype < ApplicationRecord      has_many :annotations      validates :name, presence: true, uniqueness: true, length: { minimum: 5 }  end  

Params

def annotation_params   params.require(:annotation).permit(:name, :description, :file, :active, :documenttype)  end    def documenttype_params   params.require(:documenttype).permit(:name, :description, :active, annotation_attributes: [:id, :name])  end  

This is the form...

    <div class="container-fluid">    <div class="row">      <div class="col-md-6">        <%= simple_form_for @annotation,  html: { class: 'form-horizontal', multipart: true },          wrapper: :horizontal_form,          wrapper_mappings: {              check_boxes: :horizontal_radio_and_checkboxes,              radio_buttons: :horizontal_radio_and_checkboxes,              file: :horizontal_file_input,              boolean: :horizontal_boolean            } do |f| %>              <%= f.error_notification %>                <%= f.input :name, placeholder: 'Enter name' %>                <%= f.input :description, placeholder: 'Description' %>                <%= f.association :documenttype %>              <%= f.input :active, as: :boolean %>              <% if @annotation.file.blank? %>              <%= f.input :file, as: :file %>              <% else %>            <% end %>              <%= f.button :submit %>            <% unless @annotation.file.blank? %>            <%= link_to ' Annotate', annotations_path, :class => "btn btn-default" %>            <% end -%>          <% end %>          <p><br><%= link_to 'List' , annotations_path %></p>        </div>          <div class="col-md-6">          <% unless @annotation.file.blank? %>            <%= image_tag @annotation.file.url(:large) %>          <% end %>        </div>      </div>  

Insert a footer in all pages while exporting to word from rails

Posted: 05 Sep 2016 05:03 AM PDT

I am building a rails app. I use the gem "htmltoword" to export to Word document.

The number of pages in the exported doc depends on the no:of records in the DB. I want a content in footer in all the pages of the exported document.

Is there any way to do this?

Add extra filter in spree order backend rails 4

Posted: 05 Sep 2016 04:21 AM PDT

I am using Spree 3-1 stable version In admin section I had added the filter for country in orders

<div class="row">      <div class="col-md-4">        <div class="form-group">          <%= label_tag Spree.t(:country) %>          <%= select_tag :country_ids, options_from_collection_for_select(@countries, :id, :name, params[:country_ids]), :class => 'select2 js-filterableh' %>      </div>    </div>  

and in spree/admin/orders_controller_decorator.rb i have included following code

def index      params[:q] ||= {}      @countries = Spree::Country.order(:name)      params[:q][:ship_address_country_id] = params[:country_ids] if params[:country_ids].present?        params[:q][:completed_at_not_null] ||= '1' if Spree::Config[:show_only_complete_orders_by_default]      @show_only_completed = params[:q][:completed_at_not_null] == '1'      params[:q][:s] ||= @show_only_completed ? 'completed_at desc' : 'created_at desc'      params[:q][:completed_at_not_null] = '' unless @show_only_completed        # As date params are deleted if @show_only_completed, store      # the original date so we can restore them into the params      # after the search      created_at_gt = params[:q][:created_at_gt]      created_at_lt = params[:q][:created_at_lt]        params[:q].delete(:inventory_units_shipment_id_null) if params[:q][:inventory_units_shipment_id_null] == '0'        if params[:q][:created_at_gt].present?        params[:q][:created_at_gt] = begin                                       Time.zone.parse(params[:q][:created_at_gt]).beginning_of_day                                     rescue                                       ''                                     end      end        if params[:q][:created_at_lt].present?        params[:q][:created_at_lt] = begin                                       Time.zone.parse(params[:q][:created_at_lt]).end_of_day                                     rescue                                       ''                                     end      end        if @show_only_completed        params[:q][:completed_at_gt] = params[:q].delete(:created_at_gt)        params[:q][:completed_at_lt] = params[:q].delete(:created_at_lt)      end       @search = Spree::Order.accessible_by(current_ability, :index).ransack(params[:q])        # lazyoading other models here (via includes) may result in an invalid query      # e.g. SELECT  DISTINCT DISTINCT "spree_orders".id, "spree_orders"."created_at" AS alias_0 FROM "spree_orders"      # see https://github.com/spree/spree/pull/3919      @orders = @search.result(distinct: true)                       .page(params[:page])                       .per(params[:per_page] || Spree::Config[:orders_per_page])      respond_to do |format|        format.html do        end        format.csv do          @template_name = params[:template_name]          @reporter = UnfulfilledOrdersReporter.new(@search.result(distinct: true).unfulfilled, template_name: @template_name)          send_data @reporter.to_csv, type: 'text/csv; charset=utf-8; header=present',                                      disposition: "attachment; filename=unfulfilled-#{@template_name}-orders.csv"        end        # format.csv { send_data @orders.to_csv, :type => 'text/csv; charset=utf-8; header=present',:disposition => "attachment; filename=unfulfilled_orders.csv" }      end      # Restore dates      params[:q][:created_at_gt] = created_at_gt      params[:q][:created_at_lt] = created_at_lt    end  

but its not filtering my orders according to country. Please guide me how to solve issue.

How to create conditional for attribute that equals current month?

Posted: 05 Sep 2016 04:17 AM PDT

How to only show <b>September</b> if there is a challenge that has a deadline, t.date "deadline", set for the current month?

controller

@challenges = current_user.challenges.unaccomplished.order("deadline ASC").select{ |challenge| challenge.deadline.month == Date.current.month }  @current_month = (@challenges).group_by { |t| [t.deadline.year, t.deadline.month] }  

view

<% if @current_month[Date.current.month].present? %> # This is not currently being triggered even though their is a challenge with a deadline in the current month.    <b>September</b>  <% end %>  

disable input on checkbox in rails app

Posted: 05 Sep 2016 05:09 AM PDT

I have a date input dropdown on a form in my rails application.

I'd like there to be a checkbox that- when checked/selected by the user- will (#1) disable the date input and (#2) populate the date input with the current date.

I've looked at previous SO answers to get an idea of how to do this and here's what I tried to accomplish #1:

app/assets/javascripts/application.js     //= require jquery   //= require bootstrap   //= require jquery_ujs   //= require turbolinks   //= require_tree .    $(document).on('change', '#availableNow', function(){      debugger;      if($(this).prop('checked')){          $('#fromDatePicker').attr('disabled', 'disabled');      } else {          $('#fromDatePicker').removeAttr('disabled');      }  });  

In the form...

app/views/apartments/_form.html.erb       <div class="field">        <%= f.label :available_now %>        <%= f.check_box :available_now, id:"availableNow" %>      </div>      <div class="field">        <%= f.label :to_date %><br>        <%= f.date_select :to_date, {:include_blank => true, :default => nil, :start_year => Date.today.year, :end_year => Date.today.year + 4, :order => [:month, :day, :year] }, id:"fromDatePicker" %>      </div>  

Rails generates 3 dropdown menus for the date picker (day, month & year). Only month (the first dropdown) is disabled when the box is checked.

Any ideas how to get the checkbox functionality to work for all the dropdowns?

Any idea how to "grey out" the dropdowns once they are disabled?

Thanks in advance!

assert_template fails after switching to Polymorphic Associations

Posted: 05 Sep 2016 06:26 AM PDT

It is probably something silly simple but I simply can not figure it out. Here is my situation: after adding a new db I realized that it would be the best to change an already existing one, so that it now uses polymorphic associations. Of course after I changed it, pretty much everything else went to hell. I managed though to fix all but one minor problem. The integration test now fails and I simply dont know why since the page itself still works perfectly fine...

def setup    @user=users(:michael)    @clip=clips(:Michi_clip_one)    log_in_as(@user)  end    test "successful edit" do    get edit_clip_path(@clip)    assert_template "clips/edit"    ....      FAIL["test_successful_edit", ClipEditTest, 2.686249095015228]  test_successful_edit#ClipEditTest (2.69s)  expecting <"clips/edit"> but rendering with <[]>  test/integration/clip_edit_test.rb:13:in `block in <class:ClipEditTest>'  

Since I really have no idea where lies the problem, I will simply add a few things of which I think that they might be related.

Michi_clip_one:    adress: "nfWlot6h_JM"    owner: michael    description: "MyText"  

.

class Clip < ApplicationRecord    belongs_to :owner, polymorphic: true    default_scope -> { order(created_at: :desc) }    validates :adress, presence: true, uniqueness: {scope: :owner}    before_save { self.adress=adress.split("=").last }    validates :owner, presence: true  end  

.

class ClipsController < ApplicationController      before_action :logged_in_user, only: [:new, :destroy, :edit, :update, :create]    before_action :correct_user, only: [:destroy, :edit, :update]      def edit      @clip=current_user.clips.find_by(id: params[:id])    end  

If you need other lines of code to figure the problem out, I'll be happy to add it.

Ruby on Rails: Why doesn't my embedded image display in Gmail or Office 365?

Posted: 05 Sep 2016 03:45 AM PDT

I'm trying to embed images within HTML emails so that they display inline, but for some reason the image does show in Outlook software but not in Gmail (online) or Office 365 (online). I have been referring to http://api.rubyonrails.org/classes/ActionMailer/Base.html as well as the SO question What is the right way to embed image into email using Rails?

And my code is the following:

environments/development.rb and production.rb:

config.action_mailer.asset_host = "http://localhost:3000"  

Email view:

<%= image_tag('logo.jpg') %>  

This displays the image in Outlook:

enter image description here

But not in Gmail or Office 365:

enter image description here

In the log I get the following img src for this:

<img src="http://localhost:3000/assets/logo-9b88158fa35240340cc52aa5d01800b12e6e1de5ddb99e246bd0583c7a5611cd.jpg" alt="Logo" />

I have tried a variety of approaches from different people, which include the SO questions:

Unable to render inline attachments in ActionMailer Rails attachments inline are not shown correctly in gmail Send HTML emails with inline images with ActionMailer

But none of them seem to solve my issue.

The code I have tried is:

(Attempt 1)

Mailer:

def send_email(email, unsubscribe)      @url  = 'http://localhost:3000/users/login'      @email = email      @unsubscribe = unsubscribe        attachments.inline['logo.jpg'] = File.read('C:/Sites/MySite/app/assets/images/logo.jpg')      mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)    end  

Email View:

<%= image_tag attachments['logo.jpg'].url -%>  

Log:

<img src="cid:57cd4b6a997ae_25703efc6dc786d@My-Laptop.mail" />    ----==_mimepart_57cd4b6a9af1e_25703efc6dc78787  Content-Type: image/jpeg;   filename=logo.jpg  Content-Transfer-Encoding: base64  Content-Disposition: inline;   filename=logo.jpg  Content-ID: <57cd4b6a997ae_25703efc6dc786d@My-Laptop.mail>    QzovU2l0ZXMvRWFzeU1haWwvYXBwL2Fzc2V0cy9pbWFnZXMvbG9nby5qcGc=    ----==_mimepart_57cd4b6a9af1e_25703efc6dc78787--  

(Attempt 2)

Mailer:

def send_email(email, unsubscribe)      @url  = 'http://localhost:3000/users/login'      @email = email      @unsubscribe = unsubscribe        # THE BELOW LINE      attachments.inline['logo.jpg'] = File.join(Rails.root, 'app/assets/images/logo.jpg')      mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)    end  

Email View:

<%= image_tag attachments['logo.jpg'].url -%>  

(Attempt 3)

Mailer:

def send_email(email, unsubscribe)      @url  = 'http://localhost:3000/users/login'      @email = email      @unsubscribe = unsubscribe      attachments.inline['logo.jpg'] = {                                  :data => File.read('C:/Sites/MySite/app/assets/images/logo.jpg'),                                  :mime_type => "image/jpg",                                  :encoding => "base64"      }      mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)    end  

Email View:

<%= image_tag attachments['logo.jpg'].url -%>  

This gives me a UTF error

(Attempt 4)

Mailer:

  def send_email(email, unsubscribe)      @url  = 'http://localhost:3000/users/login'      @email = email      @unsubscribe = unsubscribe      attachments.inline["logo.jpg"] = {          mime_type: "image/jpg",          content: Base64.encode64(File.read(Rails.root.join("app/assets/images/logo.jpg")))      }      mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)    end  

View:

<%= image_tag "data:image/jpg;base64,#{attachments['logo.jpg'].url}" %>  

Log:

<img src="data:image/jpg;base64,cid:57cd4c32e96d0_25704cedd5878982@My-Laptop.mail" />    ----==_mimepart_57cd4c32ea670_25704cedd5879035  Content-Type: image/jpg  Content-Transfer-Encoding: base64  Content-Disposition: inline;   filename=logo.jpg  Content-ID: <57cd4c32e96d0_25704cedd5878982@My-Laptop.mail>    aVZCT1J3bz0K    ----==_mimepart_57cd4c32ea670_25704cedd5879035--  

But none of these seem to work, its also worth adding that only the code at the top shows the image in Outlook, all the others stop me from seeing the image in Outlook, Gmail, and Office365.

Can someone please help me with this issue as I can't make sense of it.

I am using Rails 4.2.6

Using link_to in a rake task gives a no method - including helpers doesn't work

Posted: 05 Sep 2016 04:35 AM PDT

I have a rake task that I want to be sending emails to users using intercom. The issue I am having is that the link_to method does not exist.

I included the url_helpers at the top (not sure if its the right place). The error I am getting is: NoMethodError: undefined methodlink_to' for main:Object`

Please let me know if this is possible and if I am doing anything wrong.

here is the rake task:

include Rails.application.routes.url_helpers    namespace :example do  desc "TODO"  task affiliate_bonus: :environment do    User.all.each do |user|    if user.invited && user.invited.size > 0      user_affiliate_bonus = AffiliateBonu.where(inviter_id: user.id)        @the_user_af_bonus = 0      @total_affiliate_bonus = 0        user_affiliate_bonus.each do |ab|        @total_affiliate_bonus = @total_affiliate_bonus.to_f + ab.btc_bonus_amount          if ab.fulfilled == false          @the_user_af_bonus = @the_user_af_bonus.to_f + ab.btc_bonus_amount            if user.btc_wallet_address            ab.fulfilled = true            ab.save!          end        end      end        if @the_user_af_bonus >= 0 && user.affiliate_subscription          @intercom = Intercom::Client.new(app_id: ENV["INTERCOM_APP_ID"], api_key: ENV["INTERCOM_APP_KEY"])        user_receive = @intercom.users.create(email: user.email, user_id: user.id, :signed_up_at => Time.now.to_i)          referral_link_text = link_to("https://www.example.com/ref/#{user.referral_link}", "https://www.example.com/ref/#{user.referral_link}")        unsubscribe_text = link_to("click here", {:controller => "users", :action => "affiliate_unsubscribe", :user_id => user.id })        balance_text = link_to('Balance', "https://example.com/users/balance")          text =         "          <% if user.first_name %>          <p>Dear <%= user.first_name %>,</p>          <% else %>          <p>Dear Customer,</p>          <% end %>            <p>            Your referral link: #{referral_link_text} has generated $ <%= @bonus %> for you this week.             <% if @bonus > 0 %>              This amount was sent to your #{balance_text}.            <% end %>          </p>            <p>Regards,</p>            <p>George @<strong>Kaboom</strong></p>            <p>--<br>          PS. You are receiving this email update because your link has been used to sign up.</p>            <p>To unsubscribe from your profit reports, #{unsubscribe_text}.</p>        "          @intercom.messages.create({ :message_type => 'email', subject: "Your Weekly Referral Earnings Report", :body => text, :template => "plain", :from => { :type => 'admin', :id   => "55070" }, :to => { type: "user", :id => user_receive.id } })      end    end  end  end  end  

Active admin habtm filter with text field

Posted: 05 Sep 2016 03:25 AM PDT

I have an association

  class School < ActiveRecord::Base      has_and_belongs_to_many :standards    end  

In my active admin page for standards, I need to have a filter for schools with a text field for typing the school id. (Having a dropdown as schools filter is not feasible since I've thousands of schools in my db). I need something like:

  filter :schools_id  

Please help

Rails and MySQL - structure Product with sizes and prices

Posted: 05 Sep 2016 03:30 AM PDT

What is the proper way to structure models and migrations in Rails so I can have relationships like this:

Relationships

I think the image is clear enough but:

  1. One product can have different sizes
  2. A size can have different prices dependent on the product it is associated with.

I am in a school project and the only guy who has ever done something with code, and we need to structure something similar to this (it's biological but the idea is the same).

Would generating:

For product:

rails generate model Product name:string    class Product < ApplicationRecord      has_many :sizes      has_many :prices  end  

For size:

rails generate model Size size:string product:references    class Size < ApplicationRecord      has_many :products      has_many :prices  end  

For price:

rails generate model Price price:decimal size:references product:references    class Price < ApplicationRecord      has_many :sizes      has_many :products  end  

solve my problem?

I am in the middle of reading this but it is not helping.

How to allow users to define arbitrary number of fields in Rails

Posted: 05 Sep 2016 03:09 AM PDT

I'm building a CMS where Administrators must be able to define an arbitrary number fields of different types (text, checkboxes, etc). Users then can fill those fields and generate posts.

How can this be done in Rails? I guess that the persistence of these "virtual" attributes will be done in a serialised attribute in the database. But I am not sure how to struct the views and controllers, or where the fields should be defined.

Why is the link_to code adding same comment twice?

Posted: 05 Sep 2016 02:55 AM PDT

I am trying to use JavaScript with jquery in rails to update a div without reloading the page. Its working but the comment is being created twice. I know something is wrong in the form partial but couldn't figure it out. Any help?

The following are the files -

_new_comment.html.erb

<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %>        <div>          <%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %>            <%= f.hidden_field :post_id, :value => post.id %>            <span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span>      </div>    <% end %>  

comments_controller.rb

def create      @comment = Comment.new(comment_params)      @comment.user_id = current_user.id        if @comment.save          flash[:notice] = 'Comment added sucessfully'          respond_to do |format|              format.html { redirect_to home_posts_url }              format.js          end      end  end  

create.js.erb

$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>');  $("#comment-new-83")[0].reset();  

home.js

jQuery.ajaxSetup({      'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}   })    $(document).ready(function() {      $("#comment-new-83").submit(function() {          $.post($(this).attr("action"), $(this).serialize(), null, "script");          return false;      })  })  

How to get the user that published the comment and time it was created from the database so I can present it to the view

Posted: 05 Sep 2016 03:22 AM PDT

I'm creating a forum. I have successfully created a Post model presenting posts in the html view with the user email and created_at time. I have also created a Comment model for replying to posts. I've been following a tutorial and understand most of it, but am lost in now getting the user and created_at values of the comments from the database so I can display them. Even though I did it with the post model, it's different because I'm using partials that display in the show html view from the Post controller, and it's confusing me that both the post and comments are displaying in the post controller show view. (i.e. the comments don't have their own show view). I'm a newbie. Any help would be appreciated. Thank you.

routes.rb

Rails.application.routes.draw do      devise_for :users        resources :posts do           resources :comments      end        root 'posts#index'  end  

Migration for create_comments

class CreateComments < ActiveRecord::Migration[5.0]      def change          create_table :comments do |t|              t.text :comment              t.references :post, foreign_key: true              t.references :user, foreign_key: true                t.timestamps          end      end  end  

comments_controller.rb

class CommentsController < ApplicationController        def create          @post = Post.find(params[:post_id])          @comment = @post.comments.create(params[:comment].permit(:comment))          @comment.user = current_user        if @comment.save          redirect_to post_path(@post)      else          render 'new'      end      end  end  

_form.html.haml

= simple_form_for([@post, @post.comments.new]) do |f|      = f.input :comment      = f.submit  

models/comment.rb

class Comment < ApplicationRecord      belongs_to :post      belongs_to :user  end  

show.html.haml

#post_content      %h1= @post.title        - if user_allowed_post          = link_to "Delete", post_path(@post), method: :delete, data: {       confirm: "Are you sure you want to delete this?"}, class: "button"          = link_to "Edit", edit_post_path(@post), class: "button"      - else          %br      %br      %br      %p= @post.content      %p          Published          = time_ago_in_words(@post.created_at)          by          = @post.user.email        #comments          %h2              - if @post.comments.size == 1                  = @post.comments.size                  Comment              - else                  = @post.comments.size                   Comments              = render @post.comments              %h3 Reply to thread          = render "comments/form"  

Let me know if you need any other files or info.

word.charAt is not a function, Datatable error

Posted: 05 Sep 2016 03:50 AM PDT

I have integrated datatable in my Rails app (4.2.4) like this:

application.js

//= require datatables.js  //= require ../metronic/assets/global/plugins/datatables/media/js/jquery.dataTables.js  //= require ../metronic/assets/global/plugins/datatables/media/js/dataTables.bootstrap.js  

An example of use is the index page:

<table id="students" class="datatable  table table-striped table-hover table-datatable">                  <thead>                      <tr>                          <th class="left">Nome</th>                          <th class="left">Cognome</th>                          <th class="left">Classe</th>                          <th class="left">Codice Fiscale</th>                          <th class="left">Indirizzo</th>                          <th class="left">Email</th>                          <th class="left">Cellulare</th>                            <th/>                      </tr>                  </thead>                    <tbody>                      <% @students.each do |student| %>                      <tr>                          <td class="left"><%= student.nome %></td>                          <td class="left"><%= student.cognome %></td>                          <td class="left"><%= student.sigla_classe%></td>                          <td class="left"><%= student.codice_fiscale %></td>                          <td class="left"><%= student.indirizzo %></td>                          <td class="left"><%= student.email %></td>                          <td class="left"><%= student.cell %></td>                          <td class="right">                              <%= link_to 'Vedi', student %>                              |                              <%= link_to 'Modifica', edit_student_path(id: student) %>                              |                              <%= link_to 'Elimina', student, style:'color:#F00;', method: :delete, data: { confirm: 'Sei sicuro?' } %>                          </td>                      </tr>                      <% end %>                  </tbody>              </table>  

This is the controller:

def index          @students = Student.all          respond_to do |format|              format.html              format.pdf do                  pdf = StudentPdf.new(@students, view_context)                  send_data pdf.render,                            filename: 'Elenco Studenti',                            type: 'application/pdf',                            disposition: 'inline'              end          end        end  

If I do a search, the error disappears, I just can not figure out what I did wrong, I do not think it was wrong in the index are almost sure that the error lies in the way in which I integrated datatables.

For the rest everything works, the table is well displayed with correct pagination.

Modern architecture for Rails (and React) [on hold]

Posted: 05 Sep 2016 02:06 AM PDT

I am building simple SaaS app with web presentation like Home, Pricing, Features etc and then the complicated part with User Authentication & Dashboard and lots of back-end codes.

  1. Web presentation: I've done the web presentation with a simple demo with some little back-end code. It's running on Rails 5 and I am using ActionCable there with background jobs.

  2. User Dashboard: I wanna build now the user authentication and the complicated features - User Dashboard, some DB tables etc. I decided to use React with Rails.

Hosting on Heroku.

Question: How the modern SaaS applications work? Should I keep it separate and create own Heroku/Rails app for just the presentation and own for user dashboard to make it simple? Is there anything I could be aware with this idea?

--

I am also kind of new with React and single-page-apps. How could I build modern applications with React and Rails in the backend? Should I have a look for Flex or Redux? Should I process all the data with API and json? Should I be aware of anything? How would you build modern SaaS app in Rails?

15 comments:

  1. I read this article. I think You put a lot of effort to create this article. I appreciate your work.
    https://www.ufa365.info/

    ReplyDelete
  2. Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
    แทงบอลเต็ง

    ReplyDelete
  3. I must say, I thought this was a pretty interesting read when it comes to thisC topic. Liked the material. . .
    แทงบอลสเต็ป

    ReplyDelete
  4. I went over this website and I believe you have a lot of wonderful information, saved to my bookmarks
    รีวิวเว็บพนัน

    ReplyDelete
  5. My friend mentioned to me your blog, so I thought I’d read it for myself. Very interesting insights, will be back for more! เว็บแทงบอลสเต็ปไม่มีขั้นต่ำ

    ReplyDelete
  6. I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job!
    UFA365

    ReplyDelete
  7. I am often to blogging and that i actually appreciate your posts. This article has truly peaks my interest. I am going to bookmark your internet site and keep checking for first time data
    สล็อตบนมือถือ

    ReplyDelete
  8. So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site.
    แทงบาสเว็บไหนดี

    ReplyDelete
  9. Internet search engine optimization experts apply the modern analytics service, which has a positive affect a website. SEO companies are facing great competition in the SEO field. However, they introduce guaranteed SEO services to manage with the competition.

    บาคาร่าsa-gaming

    ReplyDelete
  10. his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
    แทงบาสออนไลน์

    ReplyDelete
  11. his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
    คาสิโนออนไลน์ฟรีโบนัส/

    ReplyDelete
  12. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!
    lucky-god

    ReplyDelete
  13. The role of a cultural media manager has appealed to the mass generation of socially-active internet users. It's hard not to. Especially when some might think that you can earn big bucks from posting Facebook updates. Hardly.
    สล็อตออนไลน์

    ReplyDelete
  14. Daisy Limousine provides the best black car service in the tri-state area. We can provide limo service or airport service in New Jersey, New York, Rhode Island, Massachusetts, Pennsylvania, and Connecticut. Our on-time ground transportation service will drive you pretty much from A to B anywhere in the North East of America. Give us a call or book a ride online at your convenience ประวัตินักกีฬา

    ReplyDelete
  15. Thanks for sharing such a Excellent Blog! We are linking too this particularly great post on our site. Keep up the great writing.
    ruby assignment help

    ReplyDelete