Tuesday, August 2, 2016

Rails adding a new link in the index page | Fixed issues

Rails adding a new link in the index page | Fixed issues


Rails adding a new link in the index page

Posted: 02 Aug 2016 07:48 AM PDT

i am trying to adding a new link to make a form for a join table, the link gives and error saying that no routes for that, i am using rails api

<%= link_to("Add New Alarm/List", {:action => 'new_alarm', :controller =>'alarms'}, :class => 'action new') %>  

any help please thanks in advance

Rails SQlite3 ActiveRecord select then update

Posted: 02 Aug 2016 07:48 AM PDT

I have a table where I need to select some row and update it based on a previous value, or create it if does not exist, and I need this to be safe if multiple HTTP requests are made at once regarding the same row/record.

I tried using a transaction and ActiveRecord.lock but it results in "ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked" whenever there are multiple requests. My intention was that the second request would just wait/block on the select statement and that active record would use the facilities available in the DB to do so in the most efficient manner (e.g. row locking if available, etc.).

MyModel.transaction    record = MyModel.lock.find_by(name: update_name) #name is a unique index in the SQL table    if record      # The actual manipulation is more complex than something I want to do directly in a SQL statement      record.update!(value: record.value + add_value)    else      record.create(name: update_name, value: add_value)    end  end  

Currently using Rails 5 with Ruby 2.3.1

How to disable/override "Do you want to leave this site?" alert?

Posted: 02 Aug 2016 07:42 AM PDT

I've a form in a pop-up, which is loaded by AJAX call. It is built using form_for tag of RoR. Even if I don't modify any field in it and try to navigate to another page, following alert is shown by chrome.

enter image description here

I want to disable this alert box. Is it possible? If yes, how?

I've already tried this, but it is not valid anymore.

Following are the environment settings,

Ruby version = 1.9.3  Rails version = 3.1.4  Chrome version = 52  jQuery version = 1.10.2  

Rails production error: ActionView::Template::Error (File to import not found or unreadable: photoshop-drop-shadow

Posted: 02 Aug 2016 07:32 AM PDT

I am facing this photoshop-drop-shadow while running my Rails 4.2 application in production mode.

ActionView::Template::Error (File to import not found or unreadable: photoshop-drop-shadow. Load paths:
/home/abcuser/Desktop/project/Myproject/app/assets/images
/home/abcuser/Desktop/project/Myproject/app/assets/javascripts
/home/abcuser/Desktop/project/Myproject/app/assets/stylesheets
/home/abcuser/.rvm/gems/ruby-2.3.0/gems/tinymce-rails-4.4.0/app/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/tinymce-rails-4.4.0/app/assets/source

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/tinymce-rails-4.4.0/vendor/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/remotipart-1.2.1/vendor/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/bourbon-4.2.7/app/assets/stylesheets

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/css3buttons-1.0.1/lib/assets/images

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/css3buttons-1.0.1/lib/assets/stylesheets

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/client_side_validations-4.2.5/vendor/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/jquery-ui-rails-5.0.5/app/assets/images

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/jquery-ui-rails-5.0.5/app/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/jquery-ui-rails-5.0.5/app/assets/stylesheets

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/jquery-rails-4.1.1/vendor/assets/javascripts

/home/abcuser/.rvm/gems/ruby-2.3.0/gems/compass-core-1.0.3/stylesheets):

 5:   <meta charset="UTF-8">   6:   <title><%= Rails.application.config.custom.app_name %></title>   7:   <%#= stylesheet_link_tag "marketing" %>   8:   <%= javascript_include_tag "application" %>   9:     <link rel="stylesheet" href="/marketing/css/vendor/bootstrap.css">  10:   <link rel="stylesheet" href="/marketing/css/all.css">  11:   <link rel="stylesheet" href="/marketing/css/colorbox.css">   

app/assets/stylesheets/report.scss.erb:6
app/views/layouts/public.html.erb:8:in `_app_views_layouts_public_html_erb__559746694008157479_39976240'

These are my 1st 9 lines in the report.scss.erb:

/* We broke this out of default.css file becuase it inteferring with siilar classes that were overloaded by another dev for the new version of the report/nudge show view */    @import "compass";  @import "bourbon";  @import "photoshop-drop-shadow";                                                 #this is the line it is showing error.  #master-photos-container{height:485px;margin-top:20px;}  #photos #paging-left {float:left;height:205px;width:21px;padding-top:185px;padding-left:15px;}  #photos #paging-right {float:left;height:205px;width:21px;padding-top:185px;}  

I am including report.css in application.css as:

 *= require report  

It is working fine in development mode, I don't know why it is not running production mode. I am very much worried home page, please help.

Edit/create nested resources in Formtastic (Rails)

Posted: 02 Aug 2016 07:37 AM PDT

This question is regarding Rails 4/postgresql and the app is hosted on Heroku.

I am making a Quiz-functionality on a website and I am wondering on how to implement the forms (using Formtastic) best to make this is easy as possible. I have three models:

  • Quiz (has_many :quiz_questions), e.g. "Test to see how awesome you are"
  • QuizQuestion(belongs_to :quiz, has_many :quiz_options). e.g. "1. Which is your favorite color")
  • QuizOption (belongs_to :quiz_question). e.g. "Blue"

I have set up the forms like this:

<%= semantic_form_for([:admin, @quiz], :url => admin_quiz_path(@quiz.id)) do |f| %>    <%= render 'form' , :f => f %>  <% end %>  

where the form looks like this:

<%= f.inputs %>    <h3>Quiz questions</h3>  <%= f.semantic_fields_for :quiz_questions do |qq_f| %>      <%= qq_f.inputs %>        <h4>Quiz options</h4>      <%= qq_f.semantic_fields_for :quiz_options do |qqo_f| %>          <%= qqo_f.inputs %>      <% end %>    <% end %>    <%= f.actions do %>    <%= f.action :submit %>    or go <%= link_to 'back', admin_quizzes_path %>  <% end %>  

It seems, however, not to be working the way I want. I expect to be able to see the fields of QuizQuestion and QuizOptions in this form (there are objects for those) but I don't.

More importantly is that I would like to be able to create a New QuizQuestion and subsequently QuizOption in this form. It doesn't necessarily have to be jQuery/ajax or anything but I would like to do it all from this form.

Basically, I would like my workflow to be like:

  1. Create a Quiz and add values to it. Click Create.
  2. Add QuizQuestion number one and add the values to it (like "name label"). Click Create.
  3. Add QuizOption related to QuizQuestion number one, and its "name label". Click create.
  4. Repeat for QuizQuestion/QuizOption until the Quiz is done.

How can I do this?

Cant output records to csv file

Posted: 02 Aug 2016 07:06 AM PDT

I am following Railscast 363 but am unable to replicate the functionality. So far my code structure is as follows:

CONTROLLER

def index    @search      = Campaign.search(params[:q])    @campaigns = @search.result.page(params[:page]||1)      if params[:sort]      @my_campaigns = Campaign.active      @campaigns = @my_campaigns      @campaigns = @campaigns.order(sort_column + " " + sort_direction).page(params[:page]||1)    end      respond_to do |format|        format.html      format.csv { send_data @campaigns.to_csv }    end    end  

MODEL This is an observer model (think it may be an issue however I had tried creating a standard model but it failed with a number of errors detailed at the bottom).

class CampaignObserver < ActiveRecord::Observer      def after_create(campaign)      if campaign.operator        CampaignMailer.delay(queue: :mailers).campaign_created(campaign)      end    end      def after_save(campaign)      if campaign.status_changed? && campaign.status == 'Approved' && campaign.applied_campaigns.size == 1        CampaignMailer.delay(queue: :mailers).campaign_approved(campaign)      elsif campaign.status_changed? && campaign.status == 'Rejected'        CampaignMailer.delay(queue: :mailers).campaign_rejected(campaign)      elsif campaign.status_changed? && campaign.status == 'Updated' && (campaign.status_was == 'Rejected' || campaign.status_was == 'Error')        CampaignMailer.delay(queue: :mailers).campaign_updated(campaign)      end    end      def self.to_csv(options = {})      CSV.generate(options) do |csv|        csv << column_names        all.each do |campaign|          csv << campaign.attributes.values_at(*column_names)        end      end    end  end  

VIEW - index.xls.erb Only used campaign.name to begin with.

<?xml version="1.0"?>  <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"    xmlns:o="urn:schemas-microsoft-com:office:office"    xmlns:x="urn:schemas-microsoft-com:office:excel"    xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"    xmlns:html="http://www.w3.org/TR/REC-html40">    <Worksheet ss:Name="Sheet1">      <Table>        <Row>          <Cell><Data ss:Type="String">ID</Data></Cell>          <Cell><Data ss:Type="String">Name</Data></Cell>          <Cell><Data ss:Type="String">Release Date</Data></Cell>          <Cell><Data ss:Type="String">Price</Data></Cell>        </Row>      <% @campaigns.each do |campaign| %>        <Row>          <Cell><Data ss:Type="String"><%= campaign.name %></Data></Cell>          <Cell><Data ss:Type="String"><%= campaign.name %></Data></Cell>          <Cell><Data ss:Type="String"><%= campaign.name %></Data></Cell>          <Cell><Data ss:Type="String"><%= campaign.name %></Data></Cell>        </Row>      <% end %>      </Table>    </Worksheet>  </Workbook>  

The spreadsheet is created however all that it populates is the object for each column eg. #. Any suggestions?

NOTE:

When i tried to create the following model the view started throwing errors which did not occur before.

class Campaign < ActiveRecord::Observer      def self.to_csv(options = {})      CSV.generate(options) do |csv|        csv << column_names        all.each do |campaign|          csv << campaign.attributes.values_at(*column_names)        end      end    end    end  

Select option required Ruby Rails

Posted: 02 Aug 2016 07:05 AM PDT

I have a mix of ruby rails code I have a form with a selection option that i want to be a required, and i want to validate. If user do not select anything i want to validade with a error message. However, I try to copy past code from internet, I'm new at ruby rails and I still not have a error message. I also check that i use 'required' , or if i use 'validates_presence_of' doesn't make difference because it's a submit form (i think)

test_filteR_form.rb

class TestFilterForm < ApplicationForm      attribute :model,                 String    validates_presence_of :model  end  

.html.erb

  <%= f.input :fill_form_error_message,:as => :hidden, :input_html => { :value =>I18n.t('test.fill_form_error') } %>    <%= f.input :model, label: I18n.t('test.filters.model'), autofocus: true, input_html: {class: 'input-xlarge chosen-select' }, collection: TestType.options_for_select, include_blank: true %>  

"/>

controller

 def paginate      @test_form = TestForm.new(params)      unless @test_form.valid?        @model = params[:test_filter_form][:model]        @h_model = @model.pluralize + 'H'        @history, _query,  @test_fields = TestQueryService.search!(params)          session[:test_query] = _query        session[:test_klass] = @model      else        format.json { render :json => { :error => @test_form.errors.full_messages }, :status => 422 }      end  

js.coffee

 $contentDiv.on 'ajax:error', 'form[data-value]', (event, xhr, status, error) ->      data    = $.parseJSON(xhr.responseText)      $result = $(@).parents('tr').find('[data-result]')      controller.resultUpdateError xhr.status, $result.data('result'), data, $(@)      # Hide row loading spinner      $(@).parents('tr').find('span[role="result_update_spinner"]').hide()      # Hide saved form      $(@).parents('tr').find('.saved_form').hide()        resultUpdated: (result, data, $form) ->      if data.flash != undefined        # Sets a sucess message on page top        flash data.flash.type, data.flash.message        # Sets a success message on row      $fieldForm = $form.parents('tr').find(".messages")      $fieldForm.find('.controls').empty()      $fieldForm.find('.control-group .controls').css('color', 'green').append @_inlineMessage("Gravado com sucesso")        # Hide success message after some time      setTimeout ((self) ->        ->          $fieldForm.find('.control-group .controls').empty()          return      )(this), 4000  

How to implement skim engine, client-side templates

Posted: 02 Aug 2016 07:09 AM PDT

I was recommended to use skim in my project. I can't implement it right. It is said to only add skim gem to GEMFILE. I've done that, made a template task.jst.skim, but than when Im trying to render it i get ReferenceError: JST is not defined. so what I'm doing wrong?

Best way to sanitize params in controller spec

Posted: 02 Aug 2016 06:52 AM PDT

I use RSpec with FactoryGirl (to build my model) to test a controller in my application and the test fails there :

subject do    post :create, params: {      my_model: attributes_for(:my_model,                               :pictures_for_post_request)    }, session: { user_id: user.id }  end  it 'return a 200 status response' do    subject    expect(response).to have_http_status 200  end  

When the test fails it returns an http status code 400 because in my model's validation I check if an attributes of this model is between two integer values and the value passed as param is a string.

But in my controller I parse my params to get proper integers :

private    def sanitize_params    [my_params_keys].each do |k|      params[k] = params[k].to_i if params[k].nil?    end  end  

My question is : How to properly sanitize/.to_i my params in this controller spec without rewrite my function in this spec ?

Ruby hash with dates as keys

Posted: 02 Aug 2016 06:53 AM PDT

When I do this request on my database :

users_count = User.group(:created_at).count  

I then have a hash with dates as keys :

# => {2016-07-29 00:00:00 UTC=>1, 2016-07-06 00:00:00 UTC=>1, 2016-07-07 00:00:00 UTC=>1, 2016-07-13 00:00:00 UTC=>2, 2016-07-04 00:00:00 UTC=>421, 2016-07-09 00:00:00 UTC=>3, 2016-07-08 00:00:00 UTC=>2, 2016-07-22 00:00:00 UTC=>1, 2016-07-19 00:00:00 UTC=>1, 2016-07-21 00:00:00 UTC=>2}  

But then I'm not able to retrieve data by date :

date = Date.new(2016, 7, 29)  # => Fri, 29 Jul 2016  users_count[date]  # => nil  users_count.keys.first === date  # => true  users_count[users_count.keys.first]  # => 1  

Thanks for your help.

ruby version 2.2.4, Rails version 4.2.5.1

Failure/Error: expect($stdout).to receive(:puts).with

Posted: 02 Aug 2016 07:05 AM PDT

Build a method that a new customer will use when entering the deli. The take_a_number method should accept two arguments, the array for the current line of people (katz_deli), and a string containing the name of the person wishing to join the line. The method should return the person's name along with their position in line. How can I arrange so that the array for the current line is equal to the count of the names array?

katz_deli = []    def line(array)    if array[0] == nil     puts "The line is currently empty."   end  end    def take_a_number(array, name)    i=0     counter = 1    while array.count != name.length       array[i] = counter      i+=1       counter +=1     end    if array.count > 1      puts "The line is currently:"    end    name.each_with_index {|val, index| puts "#{index+1}. #{val}"}    end

Here is the Rspec file:

describe 'Deli Counter' do      let(:katz_deli) { [] }    let(:other_deli) { ["Logan", "Avi", "Spencer"] }      describe "#line" do      context "there is nobody in line" do        it "should say the line is empty" do          # This line checks the current standard output (your terminal screen)          # to make sure the correct output has been puts'ed.          expect($stdout).to receive(:puts).with("The line is currently empty.")          line(katz_deli)        end      end        context "there are people in line" do        it "should display the current line" do          expect($stdout).to receive(:puts).with("The line is currently: 1. Logan 2. Avi 3. Spencer")          line(other_deli)        end      end    end

Ruby on Rails: Add a check box for each value in database

Posted: 02 Aug 2016 07:36 AM PDT

I am trying to display checkboxes on a form that show all of the contacts for a user, so that the user can then select the contacts required. I have done this on the form so far, which displays the checkboxes but with no value:

    <% @contacts.each do |contact| %>          <% if contact.user.id == User.find(session[:user_id]).id %>              <%= f.check_box :to %>          <% end %>      <% end %>  

But when I try to change the line <%= f.check_box :to %> to <%= f.check_box :to, contact.email %> to show the email address of the contact I get the error:

undefined method `merge' for "email@123.com":String  

Is there a way around this? I have looked at multiple posts before and tried various options but none seem to help, including:

Ruby on rails f.label for a check box http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes How to add a checkbox for each row in Rails 3.2 index page?

How to configure ActiveAdmin with CanCanCan (for multiple admin roles)

Posted: 02 Aug 2016 06:32 AM PDT

I'm using Rails version 4.2.4, activeadmin and CanCanCan version 1.13.1. I'm trying to create ACL for Admin users to grant different roles for each admin user (I have role attribute for admin users enum role:[:editor, :super_admin]) but couldn't achieve it (even by trying gem Pundit adapter) and tried the following links but they look compatible with older versions of Rails:

  1. CanCan
  2. Pundit
  3. ActiveAdmin Docs

So I need simple code to create ACL integrated with these two gems activeadmin and cancan

cancan-adapter

javascript_include_tag for js.erb?

Posted: 02 Aug 2016 07:31 AM PDT

I am using rails 5.0.0 and I am trying to include a js.erb file from my public folder into an html file.

The file I want to include is located here: public/more-information.js.erb.

In my html file is there something similar to: <%= javascript_include_tag "/more-information" %> that I can use?


I am trying to render a partial view onClick. Render from assets is no longer possible(rails-js-erb-file-cannot-find-method-render), so it has been recommended to do the action from public instead. I think that may work, but I cannot actually include an js.erb file.

Thanks for any help!

Rails: Render collection: Getting current variable inside partial

Posted: 02 Aug 2016 07:09 AM PDT

I have a collection with named variable:

= render partial: 'universal_partial', collection: districts, as: :district  

Inside partial I want to get current variable:

<li><a><%= current_variable %></a></li>  

But I have universal partial, it can gets collection from diffirent places:

= render partial: 'universal_partial', collection: subways, as: :subway  

I think, that it would be as:

<li><a><%= local_assigns[as] %></a></li>  

How can I get name (symbol as) of current variable?

Rails Mailer Is not authentication with Postfix

Posted: 02 Aug 2016 06:12 AM PDT

My Email configuration is following

    config.action_mailer.raise_delivery_errors = true         config.action_mailer.delivery_method = :smtp         config.action_mailer.smtp_settings = {        address: "172.5.8.2",        port: 25,        domain: "abc.ph",        user_name: "username",        password: "password",        authentication: 'plain',        enable_starttls_auto: true       }     config.action_mailer.default_url_options = { :host => 'http://172.2.3.4' }  

I am new one with postfix mail. My postfix mail setting is following

[root@sushi-mc3 ~]# postconf -n    alias_database = hash:/etc/aliases  alias_maps = hash:/etc/aliases  command_directory = /usr/sbin  config_directory = /etc/postfix  daemon_directory = /usr/libexec/postfix  data_directory = /var/lib/postfix  debug_peer_level = 2  debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5  home_mailbox = Maildir/  html_directory = no  inet_interfaces = all  inet_protocols = all  mail_owner = postfix  mailq_path = /usr/bin/mailq.postfix  manpage_directory = /usr/share/man  mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain  mydomain = mydomain  mynetworks = 172.5.8.2/16, 127.0.0.0/8  myorigin = $mydomain  newaliases_path = /usr/bin/newaliases.postfix  queue_directory = /var/spool/postfix  readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES  sample_directory = /usr/share/doc/postfix-2.10.1/samples  sendmail_path = /usr/sbin/sendmail.postfix  setgid_group = postdrop  smtpd_sasl_auth_enable = yes  unknown_local_recipient_reject_code = 550  

But it gives us error

 FATAL #012EOFError (end of file reached):#012  

Nested form two levels deep in Rails for selecting seeded objects

Posted: 02 Aug 2016 07:11 AM PDT

I am trying to build in a form a nested form going two levels deep. It's about creating a factory. Both the first and the second level are a collection_check_boxes to select seeded objects.

Relations in words

To the first level I had it working and concretely that momentarily looks like:
A factory has many machines, through handles.

Then I wanted to add an association to the machines in the same form:
A machine has many materials, through feeds.

A factory model looks like:

    validates :name, presence: true      validates :description, presence: true      # Factory to handle machines.       has_many :handles, :dependent => :destroy      has_many :machines, :through => :handles      # Factory needs to know about materials (fed through machines).      accepts_nested_attributes_for :machine  

And the machine model is logically derived from this, but without the nested attributes for materials of course. (Materials is an endpoint here.)

Then the controller part for the form to create the factory (factory_controller.rb):

  def factory_params      params.require(:factory).permit(:name, :description,         :machine_ids => [], machines: [:material_ids => [] ])    end  

@materials also exists in the relevant actions.

and the form looks like:

<div class="w3-row">      <div class="w3-twothird" style="margin-left: 16.65%">          <%= simple_form_for @factory do |f| %>            <!-- Input -->          <%= f.input_field :name %>          <%= f.label :name %>          <%= f.error :name %>          <%= f.input_field :description, rows: 7 %>          <%= f.label :description %>          <%= f.error :description %><br><br>            <div class="w3-row w3-margin-top">            <!-- Machines card -->            <div class="w3-third w3-card w3-padding-bottom">              <h5 class="w3-text-teal w3-center">Machines</h5>              <ul class="w3-ul" id="machines">              <%= f.collection_check_boxes :machine_ids, @machines, :id, :name do |b| %>                <li>                  <%= b.label do %>                    <%= b.check_box class: "w3-check" %>                    <%= b.text %>                  <% end %>                </li>              <% end %>              </ul>            </div>            <!-- Materials card -->            <div class="w3-third w3-card w3-padding-bottom">              <h5 class="w3-text-teal w3-center">Machines</h5>              <ul class="w3-ul" id="materials">              <%= f.collection_check_boxes :material_ids, @materials, :id, :sort do |b| %>                <li>                  <%= b.label do %>                    <%= b.check_box class: "w3-check" %>                    <%= b.text %>                  <% end %>                </li>              <% end %>              </ul>            </div>            </div>            <br><br>          <!-- Zenden -->          <div class="w3-center w3-margin-bottom">            <%= f.button :button, class: "w3-btn w3-blue w3-center" %>          </div>          <% end %>      </div>  </div>  

Sorry for all the super irrelevant css.

My spec says:

Users can create new factory with associated materials on the associated machines       Failure/Error: <%= b.check_box class: "w3-check" %>         ActionView::Template::Error:         undefined method `material_ids' for #<Factory:0x007fb3f41fbad0>  

Edit

When I think about it, maybe an association one level deep is better for the materials, then in a later stage I could always associate the used materials with the used machines.

How to show selected list of items through batch action in a dialogue box , active admin gem rails

Posted: 02 Aug 2016 05:20 AM PDT

I want to show selected items in a dialogue box in active admin. Uptill now i have seen that i can achieve this by batch action. I am not able to show selected list of items in dialogue box , so that admin can verify he/she selected right items.

Pass Ruby JSON variable to javascript variable

Posted: 02 Aug 2016 06:36 AM PDT

I have created index.html.erb file and had ruby/html code in it and file is running on webrick server at localhost without using rails .

I have a Global JSON variable in my Ruby code. It looks like this :

@rails_side_json = [{ :name => 'Will', :age => 23 },{ :name => 'John', :age => 30 }].to_json

I want this to be assigned to my javascript variable which resides in script

Not succeed by writing : var javascript_side_json = <%= @rails_side_json %>

How can I achieve this?

There is no redirection after redirect_to @contract

Posted: 02 Aug 2016 06:19 AM PDT

I create new payment

def new      @contract = Contract.find(session[:contract_id])      # Register card for user      @card_preregistration = MangoPay::CardRegistration.create({          UserId: current_user.mangopay_id,          Currency: "EUR",          CardType: "CB_VISA_MASTERCARD"        })      session[:card_id] = @card_preregistration['Id']      locals card_reg: @card_preregistration    end  

pass all data to url payment server with ajax.

register_card.coffee

jQuery ->    $('#payment-form').submit (e) ->      e.preventDefault()        $this = $(this)        mangoPay.cardRegistration.init        cardRegistrationURL: $("#CardRegistrationURL").val()        preregistrationData: $("#PreregistrationData").val()        accessKey: $("#AccessKey").val()        cardData = {        cardNumber: $("#card_number").val()        cardExpirationDate: $("#card_expiration_date").val()        cardCvx: $("#cardCvx").val()      }        mangoPay.cardRegistration.sendDataWithAjax(        # URL to capture response        "http://site:8080/finialize",        # Card data        cardData,        # Result Ajax callback        (data) ->          #console.log(data)        # Error Ajax callback        (xhr, status, error) ->           alert("Payment error : " + xhr.responseText + " (" + status + " - " + error + ")")        )  

After run method payments/finialize_payment:

def finialize_payment      @contract = Contract.find(session[:contract_id])      begin      card_registration = MangoPay::CardRegistration.update(session[:card_id], {        RegistrationData: "data=#{params['data']}",        Tag: "custom tag"      })        if card_registration['Status'] != "VALIDATED"         flash[:error] = "Cannot create card. Payment has not been created."      end      #get created virtual card object      card = MangoPay::Card.fetch(card_registration['CardId'])        # create temporary wallet for user      wallet = MangoPay::Wallet.create({        Owners: [card_registration['UserId']],        Currency: 'EUR',        Description: 'Temporary wallet for payment demo'      })      # create pay-in CARD DIRECT      payIn = MangoPay::PayIn::Card::Direct.create({        CardId: card['Id'],         CreditedWalletId: wallet['Id'],        CardType: 'CB_VISA_MASTERCARD',        Culture: 'FR',        AuthorId: card_registration['UserId'],        ReturnURL: 'http://localhost:8080/',        DebitedFunds: { Amount: @contract.amount.to_i, Currency: 'EUR' },        Fees: {Amount: 0, Currency: 'EUR'},        #payment type as CARD        PaymentDetails: {CardType: card['CardType'], CardId: card['Id']},        #execution type as DIRECT        SecureModeReturnURL: 'http://test.site'      })       #if created Pay-in object has status SUCCEEDED it's mean that all is fine       if payIn['Status'] == 'SUCCEEDED'          redirect_to @contract          flash[:notice] = "Pay-In has been created successfully."               else         # if created Pay-in object has status different than SUCCEEDED           # that occurred error and display error message          flash[:notice] = "Pay-In has been created with status: #{payIn['Status']}"       end      rescue MangoPay::ResponseError => e       flash[:error] = " Code: #{ e.code } Message: #{ e.message }"    end      end  

If payIn status successed should be redirect_to @contract But the page is not reloaded. Console display render contracts/show:

Started GET "/finialize?data=fq7ztNH9ztspcfzpUGj0_V3LhW5PKCuOSJd3CnWIdMfxq6ij__ENfQKBL_aHSaveqk7FwpB65dRgiot-92qsK0CUwTIbKLWEd9f-weFksTiJZU28-RIz5QNUh_6FYHM7_uh-M22NjZ6dU5YsJBBYuA" for 10.240.0.195 at 2016-08-02 11:50:35 +0000  Cannot render console from 10.240.0.195! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  Processing by PaymentsController#finialize_payment as */*    Parameters: {"data"=>"fq7ztNH9ztspcfzpUGj0_V3LhW5PKCuOSJd3CnWIdMfxq6ij__ENfQKBL_aHSaveqk7FwpB65dRgiot-92qsK0CUwTIbKLWEd9f-weFksTiJZU28-RIz5QNUh_6FYHM7_uh-M22NjZ6dU5YsJBBYuA"}    Contract Load (3.4ms)  SELECT  "contracts".* FROM "contracts" WHERE "contracts"."id" = $1 LIMIT 1  [["id", 10]]  Redirected to http://localhost.io:8080/contracts/e7834c9a  Completed 302 Found in 2773ms (ActiveRecord: 3.4ms)      Started GET "/contracts/e7834c9a" for 10.240.1.18 at 2016-08-02 11:50:38 +0000  Cannot render console from 10.240.1.18! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  Processing by ContractsController#show as */*    Parameters: {"id"=>"e7834c9a"}  

How correct redirect_to @contract, if payIn status is Successed? Thank you for advance.

Action Cable not working after binding with ip

Posted: 02 Aug 2016 06:30 AM PDT

I have implemented action cable of rails-5 in my system and it's work fine on localhost, but when i tried to bind with ip it's give below error message.

WebSocket connection to 'ws://192.168.1.46:3002/cable' failed: Error during WebSocket handshake: Unexpected response code: 404

and in terminal log

Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)

I have made changes on my development.rb as like

config.action_cable.url = "ws://192.168.1.46:3002/cable"  

but not succeed.

please guide me where i am wrong.

tell me if you need extra information, Thanks in advance.

Passing a curl argumet -T to rest-client

Posted: 02 Aug 2016 05:04 AM PDT

I have an API call for uploading a file and I came across -T option which does the same in curl call.

curl -X PUT "assetUrl" -H "authorization" -H "x-amz-acl:amzAcl" -H "contentType" -H "x-amz-date: amzDate" -T path/to/local/file

How can I pass that -T option to rest-client library?

I can't install iconv

Posted: 02 Aug 2016 06:57 AM PDT

When I run gem install iconv, it fails as follows:

Building native extensions.  This could take a while...  ERROR:  Error installing iconv:      ERROR: Failed to build gem native extension.        current directory: /home/myname/local/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/iconv-1.0.4/ext/iconv  /home/myname/local/rbenv/versions/2.3.1/bin/ruby -r ./siteconf20160802-38989-1ie1z24.rb extconf.rb  checking for rb_enc_get() in ruby/encoding.h... yes  checking for rb_sys_fail_str() in ruby.h... yes  checking for iconv() in iconv.h... no  checking for iconv() in -liconv... no  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.  

I don't know how to fix this. What should I do?

Everything is object in Ruby? [duplicate]

Posted: 02 Aug 2016 04:28 AM PDT

This question already has an answer here:

in ruby everything is object then New method is class level method or instance level method?

Ruby on Rails: Populate dropdown with two fields of database record

Posted: 02 Aug 2016 05:04 AM PDT

In my database I have a Users table that looks something like:

 User_ID    Firstname    Surname    Company   1          Steve        Jobs       Apple   2          Bill         Gates      Microsoft  

What I am trying to do is make a drop down menu in a form that would allow a user to choose from selecting their name or their company, e.g. when Steve Jobs is logged in he can either select "Steve" or "Apple" in the drop down menu.

What I have tried so far is the following:

<%= f.select :from_name, [session[:user_id],session[:user_id]] %>  

Which obviously didn't work because it only returns the user id of the logged in user.

<%= f.select :from_name, [@user.firstname,@user.company] %>  

Which gave me the error undefined methodfirstname for nil:NilClass`

My Users controller is as follows:

class UsersController < ApplicationController  before_filter :check_authorization, :except => [:show, :new, :create, :search ]      def index      @users = User.all    end      def show      @user = User.find(params[:id])    end      def new      @user = User.new    end      def edit      @user = User.find(params[:id])    end      def create      @user = User.new(user_params)      @user.role = "customer"      if @user.save                 session[:user_id] = @user.id          # Save a copy of the email address entered by the user into the Accounts table          @account = Account.create(email: params[:user][:primaryemailaddress], user_id: session[:user_id])          redirect_to root_path      else          render 'new'      end    end      def update      @user = User.find(params[:id])        if @user.update(user_params)          redirect_to @user      else          render 'edit'      end    end      def destroy      @user = User.find(params[:id])      @user.destroy      redirect_to users_path    end      private      def user_params      params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :company, :primaryemailaddress, :password)    end    end  

And my _form.html.erb is:

<%= form_for(@email) do |f| %>    <% if @email.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:</h2>          <ul>        <% @email.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>      <p>      <%= f.label :from_name %><br>      <%= f.select :from_name, [current_user.firstname, current_user.company] %>    </p>      <p>      <%= f.label :From_Email_Address %><br>      <%= f.collection_select :account_id, Account.where(user_id: session[:user_id]),         :id,:email %>    </p>      <p>      <%= f.label :to %><br>      <%= f.text_field :to %>    </p>      <p>      <%= f.label :cc %><br>      <%= f.text_field :cc %>    </p>      <p>      <%= f.label :bcc %><br>      <%= f.text_field :bcc %>    </p>      <p>      <%= f.label :subject %><br>      <%= f.text_field :subject %>    </p>      <p>      <%= f.label :message %><br>      <%= f.text_field :message %>    </p>      <div class="actions">      <%= f.submit %>    </div>  <% end %>  

I'm not too sure how to solve this issue, can someone please help.

How to add a new column in an existing table in Rails 5?

Posted: 02 Aug 2016 06:57 AM PDT

I want to add a new column in one of my table in Rails 5. I recently renamed a column by using the following way:

rails g migration ChangeJobsTable  

then in 20160802104312_change_jobs_table.rb:

class ChangeJobsTable < ActiveRecord::Migration[5.0]    def change      rename_column :jobs, :skills, :skills1    end  end  

then

rails db:migrate  

It worked fine, but now if I want to also add a new column skills2, do I need to do it like this?

class ChangeJobsTable < ActiveRecord::Migration[5.0]    def change      add_column :jobs, :skills2    end  end  

Please correct me if I am wrong.

Ruby on Rails - Improve page with ads and images on same page

Posted: 02 Aug 2016 03:55 AM PDT

My application is a gallery-based application. Usually I have 20 images in a page with around 15 ads (I can't remove amount of images or ads)

Images are all optimized. I use Lazy load on images and defer=true, asynchronous on the ads.

Because of the ads, Images Lazy Load waits until page is loaded before start showing the images.

Is it any way I can make the content load first and ads later? Or any solution so Lazy load doesn't wait for all ads to load before it show the images?

routes issues in layout

Posted: 02 Aug 2016 03:54 AM PDT

Ok so i'm getting this error - No route matches {:action=>"search", :controller=>"drawings", :search=>"2016"} missing required keys: [:workcategory_id]

I have this in my layouts/_header

      <% unless @workcategories.nil? %>          <% @workcategories.each do |workcategory| %>            <li><%= link_to workcategory.name, search_workcategory_drawings_path(search: workcategory.name) %></li>          <% end %>  

my drawing model

belongs_to :workcategory  def self.search(params)      drawings = Drawing.where("name like ?", "%#{params[:search]}%")      drawings  end  

and this is the part of the controller where things should be happening

def search      @drawings = Drawing.search(params)  end  

lastly my routes

  resources :workcategories do      resources :drawings do        collection do          get :search        end      end    end  

So the issue is, that when i go on any page - home, admin panel etc .. i get that error 'No route matches {:action=>"search", :controller=>"drawings", :search=>"2016"} missing required keys: [:workcategory_id]'. I don't understand why it's trying to 'build' the search path already, although i'm not trying to access it. I hope i'm making sense ...

rails display the records list in index page

Posted: 02 Aug 2016 04:19 AM PDT

I need to display all the customer in a index page in a csv format.

 def self.customer_list      CSV.generate do |csv|        csv << column_names        all.each do |customer_detail|        csv << customer_detail.attributes.values_at(*column_names)          end        end      end   end       def index      @customer_details = CustomerDetail.all      respond_to do |format|        format.html        format.csv { render text: @customer_details.customer_list }      end    end  

The problem is the page is redirecting to the index page.But it did not show the records in the index page.It shows an empty index page.I dont know how to solve this.

Autocomplete does not turn off

Posted: 02 Aug 2016 03:30 AM PDT

I have a form:

<%= form_tag("/users/submit_users_form", method: "post", class: "form-container", :autocomplete => 'off')    

which renders as:

<form class="form-container" autocomplete="off" action="/users/submit_users_form" accept-charset="UTF-8" method="post">  

and then I have the text_field_tag and password_field_tag:

<%= text_field_tag 'your_email', '', :required => true, :autocomplete => 'off' %>  <%= password_field_tag 'your_password', '', :required => true, :autocomplete => 'off' %>  

which render as:

<input type="text" name="your_email" id="your_email" value="" required="required" autocomplete="off">    <input type="password" name="your_password" id="your_password" value="" required="required" autocomplete="off">  

(even the password value is set to "")

So I have set all to autocomplete off. Now when I visit the website I get this:

enter image description here

Any clue why the autocomplete is still on?

No comments:

Post a Comment