Thursday, June 9, 2016

Date not showing in rails app when requesting year field | Fixed issues

Date not showing in rails app when requesting year field | Fixed issues


Date not showing in rails app when requesting year field

Posted: 09 Jun 2016 06:59 AM PDT

I have a data type called:

t.date :finishdate  

And I have a select field:

<%= f.select :finishdate, (Time.zone.now.year - 10)..(Time.zone.now.year) + 5,{}, class: "form-control" %>  

But i can't seem to display the year? at the moment I'm using:

<%= w.finishdate %>  

But nothing displays, I have also tried:

<%= w.finishdate.year %>  

But then get a error

undefined method `year' for nil:NilClass  

Any ideas?

Rails controller - execute action only if the two methods inside succeed (mutually dependent methods)

Posted: 09 Jun 2016 06:58 AM PDT

I have a Controller with a method called 'actions'. When the app goes inside the method 'example_action', it implements a first method (1) update_user_table and then (2) another update_userdeal_table. (both will read and write database)

My issue is the following: in case of timeout in the middle of the controller, I want to avoid the case where the User table (via method 1) is updated but the UserDeal table is NOT (via method 2). In my app, for mobile users if they're in a subway with internet connection, they launch the request that goes through 'example_action' controller, performs successfully the first method (1) but then they enter a tunnel for 60 seconds with very very low (<5b/sec) or NO internet connection, so for UX reasons, I timeout the request and display to the user 'sorry too long, try again'. The problem is that the "damage" is already here in the database:) => (1) was already performed but not (2). And in my app it is totally out of question to update the User table if the Userdeal was not updated (it would create data consistency issues...)

I need the two methods (1) and(2) to be "mutually dependent": if one does not succeed, the other one should not be performed. It's the best way I can describe it.

In practice, as (1) happens first, if (1) fails, then (2) won't be performed. Perfect.

The problem is if (1) succeeds and (2) is not performed. How can I say to Rails, if (2) is not performed successfully, then I don't want to execute any of the things inside the block 'example_action'.

Is that possible ?

class DealsController < ApplicationController    def example_action      update_user_table      update_userdeal_table       end      private    def update_user_table      # update the table User so it needs to connect to internet and acces the distant User table    end    def update_userdeal_table      # update the table UserDeal table so it needs to connect to internet and access the distant UserDeal table    end  end  

If condition not processed as expected in rails

Posted: 09 Jun 2016 06:56 AM PDT

I have my code as below

<% reported_type = 4 %>  <%=    if reported_type == 1      link_to "1 is true", true_path    else      link_to "1 is false", false_path    end      if reported_type == 2      link_to "2 is true", true_path    else      link_to "2 is false", false_path    end      if reported_type == 3      link_to "3 is true", true_path    else      link_to "3 is false", false_path    end  %>  

Expected Output: 1 is false2 is false3 is false

But actual output is 3 is false

When I comment out the third if ... else block, I get 2 is false. If it is because of <%= ... %>, then no if statement must be rendered, right?

As I am new to Rails, I can't figure out why only the last if statement is rendered. If I mix <%= ... %> and <% .. %>, my code will not look nice (As I require every block to be executed). Please help me out.

Testing cancan permissions

Posted: 09 Jun 2016 06:37 AM PDT

I have the following permissions in my ability class for a limited admin user.

can :manage, :all  cannot :manage, Project  

Why does the test cases below keep failing?. Limited admin does not have the permission to manage all. He cannot manage Project.

context 'when the user is a limited admin' do    let(:user)      { create(:user, roles: [limited_admin]) }    subject(:user_ability) { Ability.new(user, controller) }      it{ is_expected.not_to be_able_to(:manage, :all) }  end  

However, The test case below passes.

context 'when the user is a limited admin' do    let(:user)      { create(:user, roles: [limited_admin]) }    subject(:user_ability) { Ability.new(user, controller) }      it{ is_expected.to be_able_to(:manage, :all) }    it{ is_expected.not_to be_able_to(:manage, Project) }  end  

Nested render is not called after render partial in controller

Posted: 09 Jun 2016 06:29 AM PDT

I created a partial

<div style="<%= render 'kreditzeitraum_layout_properties', :kreditzeitraum => kreditzeitraum %>">      <div class="scs-mitarbeiter-row dropzone" id="mitarbeiter_row_<%= kreditzeitraum.id %>">      <% kreditzeitraum.gesetzt_aufs.each do |gesetzt_auf| %>          <%= render 'mitarbeiter', :gesetzt_auf => gesetzt_auf %>      <% end %>    </div>    <% if @zoom_factor >= 1.3 %>        <div class="scs-burndown-row" id="burndownchart_<%= kreditzeitraum.id %>">          <%= render 'personalgeld_burndown', :kreditzeitraum => kreditzeitraum %>        </div>    <% end %>    </div>  

in which again are partials. While I am loading this page on my own via a click on a button in the navigation everything works as expected.

In a further step I update the DB via an ajax call. This works fine. Since the data is updated I want to display the change. So I do again an ajax call which routes to this controller

def refresh_kreditzeitraum        ...        render 'kreditzeitraum_single', locals: { kreditzeitraum: @kreditzeitraum }    end  

But in the resulting page any render from the partial I have posted above is empty. What is wrong there?

How to push object into relation collection in seeds.rb

Posted: 09 Jun 2016 06:48 AM PDT

I have three models: Match, Broadcast and Channel. Match and Channel are associated with has_many :throught relation.

In rails console it's possible to do Match.find(3) << Channel.find(1) but in seeds.rb this line do nothing after running rake db:seed.

How to add object to collection in seeds file?

Edit:

It was typo. I forgot to add .channels. Line should look like this: Match.find(3).channels << Channel.find(1).

How add nested attributes in seed file

Posted: 09 Jun 2016 06:23 AM PDT

I have model exhibit and exhibit have quiz. In quiz we have questions and answers belongs to it. I used nested attributes.

Where I make mistake, because wright now after rake db:seed rails add me only last line in Question 1

e1 = Exhibit.create(  title: 'TITLE',   author:  'PICASOO',  date_of_origin: '300',   description: 'LOREM IPSUM',   ex_id: '1',  type: nil,      questions_attributes:[      content: "QUESTION 1?",          answers_attributes:[          content: "ANSWER 1",          correct: true,          content: "ANSWER 2",          correct: false, # if it's correct answer i change this var.          content: "ANSWER 3",          correct: false]      ])  

Exhibit model:

has_many :questions, :dependent=> :destroy    accepts_nested_attributes_for :questions,                                   :reject_if => lambda { |a| a[:content].blank? },                                   :allow_destroy => true  

Question model:

 belongs_to :exhibit        has_many :answers, :dependent=> :destroy        accepts_nested_attributes_for :answers,                                      :reject_if => lambda { |a| a[:content].blank? },                                       :allow_destroy => true  

Answer model:

class Answer < ActiveRecord::Base    belongs_to :question  end  

[RAILS][Javascript] Is it "clean" to use controller variables in javascript ?

Posted: 09 Jun 2016 06:50 AM PDT

I'm having a little question about convention and bests ways of doing things in rails.

Right now for a view I need to get an array of hash that I can construct way easier in my controller. I need this arry for my javascript code...

So I far i found a solution that isn't an ajax request which is this one :

var toto = #{@controller_var.to_json}  

I know that it's probably "better" of doing an ajax request or to store this variable in erb code... But I try to limit myself to do ajax requests (since this page already does a few ones) and I dislike creating hidden field to store my controller method...

Anyway, if you could give your opinion/advices on this I would really apreciate it ! :)

Best regards !

Rails/Ckeditor howto change height?

Posted: 09 Jun 2016 06:05 AM PDT

This may seem very stpd,sorry ...; rails4 /ckeditor/simpleform: somehow the body of a f.ckeditor text-area gets a style="height:200px", and I just can't find out where to change that size? Anyone a hint? thnx!

Incomplete response received from application Rails 4 Passenger error

Posted: 09 Jun 2016 05:46 AM PDT

I have a Rails 4.2.6 application with Passenger 5.0.28 on Ubuntu 14.04 x64.

After successful deployment using Capistrano, I can't open website. And I even can't find log files that will indicate the problem. After some research, I have found out that the most common problem is missing secret_key_base env var.

So here is my pretty simple apache config file:

<VirtualHost *:80>          ServerAdmin webmaster@localhost          ServerName my.server.com          DocumentRoot /var/www/my_server/current/public      PassengerRuby /home/deployer/.rvm/gems/ruby-2.2.2/wrappers/ruby          <Directory />                  Options FollowSymLinks                  AllowOverride None                  RailsEnv staging_v4          </Directory>          <Directory /var/www/my_server/current/public/>                  Options Indexes FollowSymLinks MultiViews                  AllowOverride All                  Order allow,deny                  Allow from all          Require all granted          </Directory>          ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/          <Directory "/usr/lib/cgi-bin">                  AllowOverride None                  Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch                  Order allow,deny                  Allow from all          </Directory>          ErrorLog ${APACHE_LOG_DIR}/error-v4.log          LogLevel warn          CustomLog ${APACHE_LOG_DIR}/access-v4.log combined  </VirtualHost>  

When I try to open my app In see the error: Incomplete response received from application

Logs tail -f /var/log/apache2/*

==> /var/log/apache2/access-v4.log <==  10.0.14.224 - - [09/Jun/2016:18:47:22 +0600] "GET / HTTP/1.1" 502 343 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"  10.0.14.224 - - [09/Jun/2016:18:47:23 +0600] "GET /favicon.ico HTTP/1.1" 200 1449 "http:/my.server.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"  

Error log is empty.

My application logs in /var/www/my_server/current/log also empty

So what I did so far:

  • I put actual string inside /var/www/my_server/current/config/secrets.yml
  • I added export SECRET_KET_BASE=<string> inside /etc/profile, /home/deployer/.bash_profile, /etc/apache2/envvars

Any thoughts? Where should I gather more information from server?

Slug error with Heroku

Posted: 09 Jun 2016 05:52 AM PDT

I have a site that works fine on my local host, but I have an error as soon as I try to create a new post in Heroku.

The Basics I have a model link that uses the friendly ID gem. This works perfectly fine in the local host. When I try to do the same thing on the Heroku site, I get this error.

NoMethodError (undefined method `slug' for #<Link:0x007f5fdae6c3a0>):  

This is included in my model:

extend FriendlyId  friendly_id :product, use: :slugged  

And in my migration, add_slug_to_links:

def change      add_column :links, :slug, :string      add_index :links, :slug, unique: true  end  

Not sure what's wrong. Any help would be appreciated.

Create record on click with ajax

Posted: 09 Jun 2016 05:27 AM PDT

I have a list of elements, which should create or delete a record in a table when clicked. Each element has some data attributes associated with it to create/destroy the correct record. I am wondering the correct 'rails' way to accomplish this?

Element list:

<div>      <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="1">Lisa</h3>      <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="2">Karen</h3>      <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="3">Susan</h3>      <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="4">Liz</h3>  </div>  

Move chart.js function from partial to assets folder in .coffee file

Posted: 09 Jun 2016 05:12 AM PDT

I have text block in main page, it located in _about.html.haml partial. When I click the link, text replaces by radar chart via AJAX (I use 'chart-js-rails' gem). Now the js function located in _my-chart.html.haml partial (which replaces first one) & I think it's not good enough.

So the question is: how to move this function code to assets folder in .coffee file or something like that?

P.S. I already try to move it to 'chart.js' file & use = javascript_include_tag 'chart.js' but it's not working graph doesn't render & I have empty canvas element.

views/welcome/_about.html.haml

%div{id: 'about'}    %h2 About      %p Some text      = link_to 'View chart', welcome_chart_path, remote: true  

views/welcome/chart.js.haml

$('#about').replaceWith('#{j render(partial: 'welcome/my-chart')}');  

views/welcome/_my-chart.html.haml

%div    %h2 Chart      %canvas{id: 'my-chart', width: '400', height: '400'}    :javascript    $(function() {        var ctx = $('#my-chart');      var data = {        labels: [a, b, c],        datasets: [          {data: [1, 2, 3]}        ]      };        var my_chart = new Chart(ctx, {       type: 'radar',       data: data     })   });  

controllers/welcome_controller.rb

class WelcomeController < ApplicationController      respond_to :js, only: [:chart]      ...      def chart; end    end  

How associate order with a current_user?

Posted: 09 Jun 2016 05:17 AM PDT

I'm building a store that has items and orders for each user. Right now I want to associate each order with a current_user. That is, the one that is making an order. I figured how to associate models but I can't figure out what to write that will save user_id to order model upon the creation of an order. I'm using standard Devise engine.

These are my models:

Order.rb

 belongs_to :order_status    belongs_to :user    has_many :order_items    before_create :set_order_status    before_save :update_subtotal      def subtotal      order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum    end  private    def set_order_status      self.order_status_id = 1    end      def update_subtotal      self[:subtotal] = subtotal    end  end  

order_item.rb

class OrderItem < ActiveRecord::Base    belongs_to :product    belongs_to :order      validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }    validate :product_present    validate :order_present      before_save :finalize      def unit_price      if persisted?        self[:unit_price]      else        product.price      end    end      def total_price      unit_price * quantity    end    private    def product_present      if product.nil?        errors.add(:product, "is not valid or is not active.")      end    end      def order_present      if order.nil?        errors.add(:order, "is not a valid order.")      end    end      def finalize      self[:unit_price] = unit_price      self[:total_price] = quantity * self[:unit_price]    end  end  

And in the user.rb I have: has_one :order

This is my OrderItemsController:

class OrderItemsController < ApplicationController    def create      @order = current_order      @order_item = @order.order_items.new(order_item_params)      @order.save      session[:order_id] = @order.id    end      def update      @order = current_order      @order_item = @order.order_items.find(params[:id])      @order_item.update_attributes(order_item_params)      @order_items = @order.order_items    end      def destroy      @order = current_order      @order_item = @order.order_items.find(params[:id])      @order_item.destroy      @order_items = @order.order_items    end  private    def order_item_params      params.require(:order_item).permit(:quantity, :product_id)    end  end  

Searching in scope for first name, last name or fullname in Ruby on Rails

Posted: 09 Jun 2016 05:21 AM PDT

I just started developing in Ruby on Rails and am trying to define a search scope in my User mode. With the following scope I am able to search for a user based on his first name or his last name:

  scope :_s, -> (s) {          where(      'unaccent(LOWER(email)) like unaccent(LOWER(?))      OR unaccent(LOWER(first_name)) like unaccent(LOWER(?))      OR unaccent(LOWER(last_name)) like unaccent(LOWER(?))',      "%#{s}%", "%#{s}%","%#{s}%") }  

I can't get my scope up and running to search for the full name, I thought the following would work:

  scope :_s, -> (s) {      select('(first_name || " " || last_name) as \'full_name\', *')        where(      'unaccent(LOWER(email)) like unaccent(LOWER(?))      OR unaccent(LOWER(first_name)) like unaccent(LOWER(?))      OR unaccent(LOWER(last_name)) like unaccent(LOWER(?))      OR unaccent(LOWER(full_name)) like unaccent(LOWER(?))',      "%#{s}%", "%#{s}%","%#{s}%","%#{s}%") }  

But this returns

PG::UndefinedColumn: ERROR: column "full_name" does not exis

I understand that my database thinks that I am looking for a record in the database, but how can I tell it to look at the defined full_name above?

Rails error with make_flaggable

Posted: 09 Jun 2016 04:52 AM PDT

When i try to flag something with:

user.flag(page_post,:like)  

I get:

MakeFlaggable::Flagging Load (0.8ms)  SELECT  "flaggings".* FROM "flaggings" WHERE "flaggings"."flagger_id" = ? AND "flaggings"."flagger_type" = ? AND "flaggings"."flaggable_type" = ? AND "flaggings"."flaggable_id" = ? AND "flaggings"."flag" = ?  ORDER BY "flaggings"."id" ASC LIMIT 1  [["flagger_id", 3], ["flagger_type", "User"], ["flaggable_type", "PagePost"], ["flaggable_id", 9], ["flag", "like"]]     (0.2ms)  begin transaction    SQL (0.6ms)  INSERT INTO "flaggings" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2016-06-09 11:17:12.695438"], ["updated_at", "2016-06-09 11:17:12.695438"]]     (12.5ms)  commit transaction   => #<MakeFlaggable::Flagging id: 98, flaggable_type: nil, flaggable_id: nil, flagger_type: nil, flagger_id: nil, flag: nil, created_at: "2016-06-09 11:17:12", updated_at: "2016-06-09 11:17:12">  

My page_post model:

make_flaggable :like  

My user model:

make_flagger  

Agile Development with Rails 4, Chapter 10 - playtime section: Misunderstood code

Posted: 09 Jun 2016 05:44 AM PDT

I am having a problem understanding a line of code in a suggested solution in the playtime section of Chapter 10 in Agile Development with Rails 4.

For an exercise, I am supposed to create a unit test that adds duplicate products. The logic of the unit test is as follows: In the unit test, I should create a cart, add two of the same item (already declared as a fixture) to the cart, save the items then make assertions for what I expect the number of items and the total price should be. Below is the suggested solution. The problem is I don't understand this line nor its function: "assert_equal 2, cart.line_items[0].quantity". See the full test below. Thanks in advance!

test "add duplicate product" do          cart = Cart.create          ruby_book = products(:ruby)          cart.add_product(ruby_book.id).save!          cart.add_product(ruby_book.id).save!          assert_equal 2*book_one.price, cart.total_price          assert_equal 1, cart.line_items.size          assert_equal 2, cart.line_items[0].quantity      end  

Rails make_flaggable error cant flag

Posted: 09 Jun 2016 04:47 AM PDT

When i try to flag something with:

user.flag(page_post,:like)  

I get:

MakeFlaggable::Flagging Load (0.8ms)  SELECT  "flaggings".* FROM "flaggings" WHERE "flaggings"."flagger_id" = ? AND "flaggings"."flagger_type" = ? AND "flaggings"."flaggable_type" = ? AND "flaggings"."flaggable_id" = ? AND "flaggings"."flag" = ?  ORDER BY "flaggings"."id" ASC LIMIT 1  [["flagger_id", 3], ["flagger_type", "User"], ["flaggable_type", "PagePost"], ["flaggable_id", 9], ["flag", "like"]]     (0.2ms)  begin transaction    SQL (0.6ms)  INSERT INTO "flaggings" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2016-06-09 11:17:12.695438"], ["updated_at", "2016-06-09 11:17:12.695438"]]     (12.5ms)  commit transaction   => #<MakeFlaggable::Flagging id: 98, flaggable_type: nil, flaggable_id: nil, flagger_type: nil, flagger_id: nil, flag: nil, created_at: "2016-06-09 11:17:12", updated_at: "2016-06-09 11:17:12">  

My page_post model:

make_flaggable :like  

My user model:

make_flagger  

ActiveModel::Serializer Shared include list

Posted: 09 Jun 2016 04:38 AM PDT

Using active-model-serializer, I have a model which references two of the same model type:

class MyModelSerializer < ActiveModel::Serializer    embed :ids, include: false      attributes :id, :created_at      has_one :from_contact, include: true    has_one :to_contact, include: true  end  

(this is simplified code from my project)

The problem I have is that when this is serialized into my API output, I end up with two lists in the JSON for each contact list. This is compounded by this model being included by a parent model which also has other Contact references. So I end up with several lists of Contacts in my API output, all duplicating basically the same set of Contact objects.

Is there any way to convince the serializer to make all my fields use a common list of contacts in the response, rather than one list per "field"?

rails foreign key setup with AR and postgres

Posted: 09 Jun 2016 05:29 AM PDT

I just realized I have some issues when deleting parent models.

I have this setup:

user.rb

has_many :conversations, foreign_key: "sender_id", dependent: :destroy  

conversation.rb

belongs_to :sender, class_name: "User", foreign_key: "sender_id"  belongs_to :recipient, class_name: "User", foreign_key: "recipient_id"  

schema (postgres DB)

add_foreign_key "conversations", "users", column: "recipient_id"  add_foreign_key "conversations", "users", column: "sender_id"  

As you can guess if user.destroy is called and there is a conversation where the user is the recipient then it will raise PG::ForeignKeyViolation ERROR: update or delete on table conversations violates foreign key constraint...

To deal with this problem I'm planning to do the following:

user.rb

#this will solve the rails side of the problem  has_many :received_conversations, class_name: "Conversation", foreign_key: "recipient_id", dependent: :destroy  

schema (DB):

#this will solve the DB side of the problem  add_foreign_key "conversations", "users", column: "recipient_id", on_delete: :cascade  add_foreign_key "conversations", "users", column: "sender_id", on_delete: :cascade  

Is this the right way to solve this issue?

Rails migration to change empty strings to null

Posted: 09 Jun 2016 06:12 AM PDT

Say I have a db table called fruit like this:

id  name  1   ""  2   ""  3   ""  4   ""  5   ""  6   melon  

I need to write a migration to change the empty strings to null without affecting melon in this case.

Would it be something on these lines?

def change    update_column fruits, :name, null if :name => ""  end  

Pretty basic stuff I guess but I'm kinda stuck here. What is the best approach here?

before_create method in model not working - Rails4

Posted: 09 Jun 2016 04:45 AM PDT

i am unsure why my boolean is not automatically being set to false when a company is created. could one kindly advise me why.

  • i am using the before_create method in the model

you help or advise would be much appreciated

schema

ActiveRecord::Schema.define(version: ############) do    create_table "companies", force: true do |t|      t.string   "companyname"      t.string   "tel"      t.string   "email"      t.boolean  "fake"    end  end  

company.rb

Have I written the set_company_as_false method correctly?

class Company < ActiveRecord::Base    belongs_to :category_businesstype    has_many :users, dependent: :destroy      before_create :set_company_as_false      def set_company_as_false      self.fake == false      # if false it means company is not a fake/dummy company    end  end  

Terminal

Started POST "/companies" for 127.0.0.1 at 2016-06-09 12:08:11 +0100  Processing by CompaniesController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"siKCe0npwA/sICpaCSds+vxWLw1ftv7z4s3tuNITJOM=", "company"=>{"companyname"=>"Event Ninja", "companyimage"=>#<ActionDispatch::Http::UploadedFile:0x007f83a463c2c8 @tempfile=#<Tempfile:/var/folders/72/z21dh3tx6jb03dscv7m3wc_h0000gn/T/RackMultipart20160609-772-nbq6po>, @original_filename="eventnj.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"company[companyimage]\"; filename=\"eventnj.png\"\r\nContent-Type: image/png\r\n">, "email"=>"info@eventninja.io", "link"=>"https://twitter.com/eventninjaio", "tel"=>"+447961262477", "category_country_id"=>"3", "city"=>"London", "category_staff_id"=>"1", "category_companyage_id"=>"2", "category_businesstype_id"=>"1", "category_advert_id"=>"25"}, "commit"=>"Register"}     (0.1ms)  begin transaction     (0.1ms)  rollback transaction    Rendered shared/_header_signedout.html.erb (1.8ms)    CategoryCountry Load (0.3ms)  SELECT "category_countries".* FROM "category_countries"    CategoryStaff Load (0.2ms)  SELECT "category_staffs".* FROM "category_staffs"    CategoryCompanyage Load (0.2ms)  SELECT "category_companyages".* FROM "category_companyages"    CategoryBusinesstype Load (0.2ms)  SELECT "category_businesstypes".* FROM "category_businesstypes"    CategoryAdvert Load (0.3ms)  SELECT "category_adverts".* FROM "category_adverts"    Rendered companies/_form.html.erb (956.0ms)     (0.1ms)  SELECT COUNT(*) FROM "stories"    Rendered shared/_footer.html.erb (2.0ms)    CACHE (0.0ms)  SELECT "category_countries".* FROM "category_countries"    CACHE (0.0ms)  SELECT "category_staffs".* FROM "category_staffs"    CACHE (0.0ms)  SELECT "category_companyages".* FROM "category_companyages"    CACHE (0.0ms)  SELECT "category_businesstypes".* FROM "category_businesstypes"    CACHE (0.0ms)  SELECT "category_adverts".* FROM "category_adverts"    Rendered companies/_form.html.erb (605.7ms)    CACHE (0.0ms)  SELECT COUNT(*) FROM "stories"    Rendered shared/_footer.html.erb (2.4ms)    Rendered shared/_responsive_companies_form.html.erb (611.9ms)    Rendered companies/new.html.erb within layouts/application (1579.4ms)  Completed 200 OK in 10049ms (Views: 10041.4ms | ActiveRecord: 1.5ms)  

controller

class CompaniesController < ApplicationController    respond_to :html, :xml, :json    before_action :set_company, only: [:show, :edit, :update, :destroy]    #load_and_authorize_resource      def new      if user_signed_in?        if current_user.admin_pa_management_group          @user = current_user          @company = @user.company        else          redirect_to errorpermission_path        end      else        @company = Company.new      end    end      def create      @company = Company.new(company_params)      respond_to do |format|        if @company.save          format.html { redirect_to(new_user_registration_path, notice: 'Company was successfully created.') }          format.json  { render json: @company, status: :created, location: @company }        else          format.html { render action: "new" }          format.json  { render json: @company.errors, status: :unprocessable_entity }        end      end    end      private      def set_company        @company = Company.find(params[:id])      end        def company_params        params.require(:company).permit(:companyname, :tel, :email, :category_staff_id, :category_country_id, :category_advert_id, :category_businesstype_id, :category_companyage_id, :city, :town, :latitude, :longitude, :address, :image, :link, :companyimage, :postcode, :about, :linklinkedin, :fake)      end  end  

Teaplix Inventory CSV Order is not importing

Posted: 09 Jun 2016 05:08 AM PDT

I am using Teaplix To import Inventory Quantity Upload. https://www.teapplix.com/help/?page_id=4720

CSV upload

url = "https://www.teapplix.com/h/#{@account_name}/ea/admin.php?User=#{@username}&Passwd=#{@password}&Action=Upload&Subaction=inventory&upload=#{csv_url}"  response = HTTParty.post(url,        body: {}.to_json,        headers: {          "Content-Type" => "text/csv",          "Accept" => "text/csv"        }      )  

Everything i am grtting, but csv is not uploading

Getting Error

error "No such run-mode 'Upload'"  

can some one tell which way i can upload inventory csv in teaplix

How to connect to remote machine in Ruby with "raw" connection type like in PuTTY?

Posted: 09 Jun 2016 05:20 AM PDT

I want to communicate with remote printer which has IP "xxxxx" and port number "xxx". I am able to connect to printer through PuTTY and can issue the command to the printer and printer is executing those commands.

Below are the images that describes the steps that I am doing to connect to printer and issue the command to it.

enter image description here

As you can see in the above image I am using "raw" connection type.

enter image description here

Above image shows the command that I am issuing to printer after connecting it via "raw" connection type.

I want to connect to remote machine (printer) via Ruby programming language with "Raw" connection type as shown in the first image of PuTTY. But I am not able to do it. Also there are libraries for SSH and Telnet but there is no library that can connect to remote machine (printer) with "raw" connection type.

I want to know how can I connect to remote machine (printer) with "Raw" connection type like PuTTY and issue the command to the printer.

Thanks,
Sanjay Salunkhe

SMS verification after devise login, how?

Posted: 09 Jun 2016 04:08 AM PDT

I am using devise for user authentication, how i can request from user, after clicking on sign in button, to enter sms code which is automaticaly sent to his mobile phone, for successful sign in.

I followed some instructions from internet, also i made twilio and got API key, but still no idea how to finish this.

Showing first picture in each category on Rails app index page

Posted: 09 Jun 2016 05:27 AM PDT

I'm learning Rails by building a small personal Ecommerce App.

So far I have built a products page, category page, checkout page and so on.

I´m able to upload pictures and assign them to categories through this product_form.

<%= form_for @product, multipart: true do |f| %>    <% if @product.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>      <ul>    <% @product.errors.full_messages.each do |message| %>      <li><%= message %></li>    <% end %>    </ul>  </div>  <% end %>    <div class="field">    <%= f.label :name %><br>    <%= f.text_field :name %>  </div>  <div class="field">    <%= f.label :description %><br>    <%= f.text_field :description %>  </div>  <div class="field">    <%= f.label :price %><br>    <%= f.text_field :price %>  </div>  <div class="field">   <%= f.label :image %><br>   <%= f.file_field :image %>  

<div class="field">    <%= f.label :category %><br>    <%= f.select :category_id, Category.all.map { |c| [ c.name, c.id ] } %>  </div>  <div class="actions">    <%= f.submit %>  </div>   <% end %>  

Then, I can go to each category by selecting it in the _navbar.html.erb, like this.

 <ul class="dropdown-menu" role="menu">                            <% @categories.each do |category| %>             <li><%= link_to category.name, category %></li>           <% end %>        </ul>  

But the thing I want to be able to do is to display the latest uploaded picture in each category on the index page views/pages/index.html.erb so each picture will appear in its own div in a Bootstrap grid.

I´m not sure how to do that.

This is what I have come up with so far, by displaying this code in the in views/pages/index.html.erb

<% @products.each do |product| %>   <div class="col-lg-3 col-sm-6 col-xs-12 center-block " >    <%= image_tag product.image, height: "300", class: "img-responsive" %>        <div class="product_description">         <h5><%= link_to product.name, product %></h5>       <p><%= product.description %></p>       <p class="price"> <%= number_to_currency product.price %></p>       </div>         </div>   <% end %>  

and in the pages_controller.rb I have

class PagesController < ApplicationController     def index        @products = Product.all     end  end  

so my question is, how should I change the controller or the views/pages/index.html.erb to be able to only show the last uploaded picture in each category on the views/pages/index.html.erb

thanks in advance D

Devise Invitable how to provide user to set the password

Posted: 09 Jun 2016 03:12 AM PDT

I am using Devise and devise invitable gem. If a invited user who doesn't accept the invitation and request a confirmation email using the same email address, the email is confirmed and the devise doesn't ask the user to set up the password. Which I think is not good. So, how to let the user to set the password.

is there an Ajax version of Datagrid gem for Rails

Posted: 09 Jun 2016 03:11 AM PDT

I was tinkering with Mongodb (using mongoid adapter) with Rails and found out that it has less support in terms of data-tables than the standard active-record.

While looking for datagrids / datatables generators, I have found a good one named: "Datagrid" https://github.com/bogdan/datagrid

I looked at the documentation and it supported mongoid out of the box, but alas! It does not shipped with Ajax support out of the box.

Does anyone know of any alternative or easier workaround to have datatables for Mongoid based model / table in Rails?

Ruby not edit or saving from a collection_select

Posted: 09 Jun 2016 06:48 AM PDT

Please help The form does not save the collection_select and it does not edit _form.html.erb

<div class="field">    <%= f.label :company_id %><br />    <%= collection_select(:learner, :learner_id, @clients, :id, :name,    prompt: >true) %>   </div>  

learners_controller.rb

def edit    @learner = Learner.find(params[:learner_id])  end  

Rails 4 does not render my Layout

Posted: 09 Jun 2016 03:56 AM PDT

I currently mindblown regarding Layouts in Rails 4, as of now, i created a layout for my controller and it is successfully being called in my controller using the layout "layout_name"

but the problem is, whenever i redirect_to that controller it only renders the page itself not the layout on top of it.

here is my snipper of the code:

class LoginController < ApplicationController    layout "login_layout"    def index      user = User.new    end      def login_user      validate_credential = User.login(params[:user])      if validate_credential[0] == true        session[:user_firstname] = validate_credential[1][0]["firstname"].capitalize        session[:user_lastname] = validate_credential[1][0]["lastname"].capitalize        session[:user_id] = validate_credential[1][0]["id"]        session[:advisory_class] = validate_credential[1][0]["advisory_class"].capitalize        redirect_to :controller=> 'dashboard', :action=> 'home'      else        redirect_to :action=>'index'      end    end  

Take not the redirect_to in my login_user function does render the layout.

and this is my code of the logout (from another controller)

class DashboardController < ApplicationController    layout 'dashboard_layout'    def home    end      def settings    end      def students    end      def logout      session.clear      redirect_to :controller=>'login',:action=>'index'    end  

It renders the page itself but the layout for that controller is not included.

I've searched many solution but still, no hopes.

This is a pic of how the root_path looks like when being called (redirect_to) from my dashboard controller.

enter image description here

and this must be the design of my root_path. (Layout included). Take note that the URL is the same but the layout is not being rendered. but when i refresh the page it shows the layout.

enter image description here

No comments:

Post a Comment