Sunday, August 21, 2016

Heroku & Godaddy Naked domain configuration not redirecting | Fixed issues

Heroku & Godaddy Naked domain configuration not redirecting | Fixed issues


Heroku & Godaddy Naked domain configuration not redirecting

Posted: 21 Aug 2016 08:34 AM PDT

I am using ssl with my heroku app and I am using godaddy as my host.

My problem is, if I type www.mydomain.com, it redirects to (https)://www.mydomain.com which is ok.

But when I type mydomain.com it redirects to (http://)mydomain.com. So I understand that is the problem of naked domain configuration.

Till now,

I set the heroku custom domain as; www.mydomain.com as domain name and smt-somenumber.herokussl.com as dns target.

On the godaddy side, as Cname I put www and smt-somenumber.herokussl.com. as forwarding I put (https://)www.mydomain.com.

Do you think should I put (https://)smt-somenumber.herokussl.com as forwarding instead of (https://)www.mydomain.com ?

Elasticsearch with Rails importing StatementInavlid

Posted: 21 Aug 2016 08:31 AM PDT

I am using gem https://github.com/elastic/elasticsearch-rails and under initializers I have

unless client.indices.exists? index: 'history_views'  HistoryView.__elasticsearch__.create_index! index: 'id'  end    HistoryView.import  

and I get that error.

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'history_views.' in 'order clause': SELECT history_views.* FROM history_views ORDER BY history_views.`` ASC LIMIT 1000

How to get rid of that order by ?

Failed to Build Gem Extension Error Installing rails

Posted: 21 Aug 2016 07:40 AM PDT

I'm on a fresh Ubuntu installation and using the guide to install rails found here.

When I get to the final sudo gem install rails, I get this error:

    Building native extensions.  This could take a while...  ERROR:  Error installing rails:      ERROR: Failed to build gem native extension.        current directory: /var/lib/gems/2.3.0/gems/nio4r-1.2.1/ext/nio4r  /usr/bin/ruby2.3 -r ./siteconf20160821-19665-u7rxlt.rb extconf.rb  mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h    extconf failed, exit code 1    Gem files will remain installed in /var/lib/gems/2.3.0/gems/nio4r-1.2.1 for inspection.  Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nio4r-1.2.1/gem_make.out  

ruby program functionality

Posted: 21 Aug 2016 07:32 AM PDT

I'm new to ruby and struggling to understand the full functionality of this ruby script. I want to understand it and then rewrite into java or R. lastly, I got the script from hadley Github.

So I have the following questions:

. I don't really understand the ID parameter values. Is it the same from the movies table. If so why is it a string.

. I don't really understand how the genres and the genres of interest are being mapped. I understand the sql bit except in the where clase in partical "#{id}" and flatten.to_set(is this turning genres to a set)

genres_of_interest = ["Action", "Animation", "Comedy", "Drama","Documentary", "Romance", "Short"]    $ratings_map = {"." => 0, "0" => 4.5, "1" => 14.5, "2" => 24.5, "3" => 34.5, "4" => 44.5, "5" => 45.5, "6" => 64.5, "7" => 74.5, "8" => 84.5, "9" => 94.5, "*" => 100}      def genres_binary(id, db)  genres = db.execute("SELECT genre FROM Genres where movie_id = {id};").flatten.to_set  $genres_of_interest.map { |genre| (genres.include? genre) ? 1 : 0}  end     db = SQLite3::Database.open "movies_sqlite3.db"   db.results_as_hash= true    sql = "  SELECT Movies.*   FROM Movies  WHERE length > 0 and imdb_votes > 0  ORDER BY title"    i = 0     File.open("movies.tab", "w") do |out|  out << [      'title', 'year', 'length', 'budget',       'rating', 'votes', (1..10).map{|i| "r" + i.to_s},       'mpaa', $genres_of_interest  ].flatten.join("\t") + "\n"  db.execute(sql) do |row|       puts i if (i = i + 1) % 5000 == 0        out << [          row["title"],           row["year"],           row["length"],           row["budget"],           row["imdb_rating"], row["imdb_votes"], ratings_breakdown(row["imdb_rating_votes"]),           row["mpaa_rating"], genres_binary(row['id'], db)      ].flatten.join("\t") + "\n"  end  end  

E.g of the Movies table data

id/title/year/budget/length imdb_rating/imdb_votes/imdb_rating_votes/ mpaa_rating these are the columns

9/#1 Serial Killer/ 2013/30000/87/6.1/33/2000.02002/PG-13 columns data

E.g of the Genre table data

id/movie_id/genre these are the columns 440/1816/Talk-Show columns data

Please for give me, this is my first question ever on stack overflow.

Thanks

How to solve undefined method `to_key' error with collection_select - RoR

Posted: 21 Aug 2016 08:10 AM PDT

I'm trying create a collection select, but I got this error:

NoMethodError in Deal#selectuser    undefined method `to_key' for #<Conversation::ActiveRecord_Relation:0x1059f4f8>  

My controller

def selectuser      @conversation = Conversation.involving(current_user)  end  

My routes

  resources :deal, only: [:index, :new, :create, :selectuser] do       collection do        get "selectuser" # generate  get "/deal/selectuser"      end  

My view (conversation.html.erb)

<%= form_for @conversation do |f| %>    <%= collection_select(:conversation, :recipient_id, Conversation.all, :recipient_id, :title) %>    <%= f.submit  "Send", class: "btn btn-primary wide" %>  

Shoulda Matcher and has_many through: undefined method `class_name' for nil:NilClass

Posted: 21 Aug 2016 08:33 AM PDT

I'm trying to test a :has_many through relationship with Rspec and Shoulda matchers.

# student.rb  has_many :presences  has_many :calls, through: :presences    # student_spec.rb  it { should have_many(:presences) }  it { should have_many(:calls).through(:presences) }    #presence.rb  belongs_to :call  belongs_to :student    #presence_spec.rb  it { should belong_to(:call) }  it { should belong_to(:student) }    #call.rb  has_many :presences  has_many :students, through: :presences    #call_spec.rb  it { should have_many(:presences) }  it { should have_many(:students).through(:presences) }  

Only the last of these test fails, returning:

NoMethodError:  undefined method `class_name' for nil:NilClass  Did you mean?  class_eval  

I found this issue, but the solutions proposed don't help me.

How to recursively send a nested hash the :[] method for any amount of levels?

Posted: 21 Aug 2016 07:08 AM PDT

Context:

What I'm trying to do is make an Rspec shared_example called something like update response that checks a rails json response of an object and verifies that certain attributes are updated. The json response may or may not have nested attributes. The keys cannot be known ahead of time.

Example:

Say I have a hash, hsh = {one_deep: 123, nested: {a: 1, b: 2}}:

I can dynamically send the hash a key if it's one level deep.

def get_value(some_key)    hsh.send(:[], some_key)   end    get_value(:one_deep) # => 123  

I can access a nested hash if I hard code the method chain:

def get_value(some_key, another_key)    hsh.send(:[], some_key).send(:[], another_key)   end    get_value(:nested, :a) # => 1  get_value(:nested, :b) # => 2  

Desired Endstate:

# The hash key could be 'n' levels deep  #  # This doesn't work... maybe use recursion somehow?  def get_value(*some_keys)    some_keys.each do |key|      hsh.send(:[], key)    end  end      get_value(:nested, :a) # => should output 1  get_value(:nested, :b) # => should output 2  

How to edit 'pagination gem' - Rails project

Posted: 21 Aug 2016 06:34 AM PDT

I need to edit my code to contain "target: "_self". How can i do it?

This is my code.

controller:

@news = News.order(created_at: :desc).paginate(page: params[:page], per_page: 7)  

view:

<div>     <%= will_paginate @news, previous_label: "Назад", next_label: "Вперед" %>  </div>  

THIS code don't work:

<%= will_paginate @news, previous_label: "Назад", next_label: "Вперед", target: "_self" %>  

Setting up CD for a Ruby on Rails project with Bitbucket Pipelines and Docker

Posted: 21 Aug 2016 06:50 AM PDT

I'd love to set up continuous deployment in Bitbucket Pipelines for a Ruby on Rails / PostgreSQL / Sidekiq project, but I'm struggling to get my head around how it all fits together, and specifically how to get postgres working inside a Docker image. I'm very new to Docker and Pipelines.

In my Googling, Docker talks about using docker-compose to create a bundle, so I'd have a Postgres container and a Sideqik container, then link them with the app container. But I'm not sure what the difference is between a bundle and an image, and if Bitbucket Pipelines supports bundles. Eventually I want to set up deployments to a staging environment on Heroku, but for now just getting rspec spec to work in Pipelines would be nice.

Is there an existing public image that has Ruby + PostgreSQL already set up that I can use? If not, where do I start? My current Dockerfile looks like this:

FROM postgres:9.4  FROM ruby:2.3.1-onbuild  RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs postgresql-client  

I then run docker build . and docker run -it my-image /bin/bash and the following commands:

root@a84ad0e7c16b:/usr/src/app# postgres  bash: postgres: command not found  root@a84ad0e7c16b:/usr/src/app# psql   psql: could not connect to server: No such file or directory    Is the server running locally and accepting    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?  

Heroku and database management for rails

Posted: 21 Aug 2016 06:02 AM PDT

I'm getting really close to putting up my first app. However, I'm worried that because I'm so new, I won't know how to manage my database properly.

What's the best practice for managing a database on heroku? As in, backups for example. What if I really screw up something? Can I edit information like usernames, email addresses for users, etc directly in heroku or do I still do that from my terminal?

Rails: I have one controller with providing api service methods and another controller which access these api

Posted: 21 Aug 2016 06:01 AM PDT

I have one controller

class APIABCController < ActionController::API  ....  def index  ...  end  

another controller on the same app

  class RestCallController < ActionController::Base       def index          ...       end     end  

Now I want to call APIABC Controller create method using rest from RestCall Controller.

is it a good way please suggest.

I do not want ajax to call. I want rest call from one controller to another controller methods

Getting assert_select to show me what an element actually was

Posted: 21 Aug 2016 06:40 AM PDT

I have the following test:

test "users title when logged out" do    get users_path    assert_select "title", 'Correct title"  end  

If we assume that users_path returns a page with <title>Wrong title</title>, then I get the following output:

FAIL["test_users_title_when_logged_out", SiteLayoutTest, 1.0830602300120518]   test_users_title_when_logged_out#SiteLayoutTest (1.08s)          Expected at least 1 element matching "title", found 0..          Expected 0 to be >= 1.          test/integration/site_layout_test.rb:37:in `block in <class:SiteLayoutTest>'  

I would like to replace the assert_select with something like assert_equal "Correct title", page.title so that the test failure message actually shows me what the page's title is, which would make tracing the problem much easier! (Naturally, the page shows the correct title in development mode…)

However, page.title does not seem to be available, and my efforts at searching are only turning up stuff like "you can do it with Capybara", which is a bit bulky for this purpose!

Is there a way to write this test so that it shows something like Expected page title to be "Correct title" but got "Wrong title" instead? [Edit for clarity: "Wrong title" is the title in the returned page, not a literal string — that is, I need the error to tell me what was actually returned.]

ActiveRecord: Skip validation when saving multiple objects

Posted: 21 Aug 2016 08:07 AM PDT

I know I can skip validations for an individual save, like this:

User.new(name: 'John').save(validate: false)  

But how can I do that when saving multiple objects at once? Like this:

Category.create([    { name: 'Apps' },    { name: 'Songs' },    { name: 'Movies' }  ])  

Always display locales in URL in rails 4 app

Posted: 21 Aug 2016 05:08 AM PDT

So I'm using i18n gem since my rails web-app has to be available in 2 languages : FR and NL.

I made FR the default locale.

My goal is to make sure that in any circumstances, the locales (ie. /fr/ or /nl/) are always shown in the URL.

This is the case with the locale=nl but not the case with the locale=fr being the default locale.

Here an example with a user story:

  1. a user arrived on the website and has to select his/her language: let's say "FR" ("FR" being the default locale)
  2. the user can now browse the site
  3. the user visit the page "Newsfeed" page and his/her URL is http://localhost:3000/newsfeed

With this example, the URL should have been http://localhost:3000/fr/newsfeed (with the /fr/ in the URL)

These are my routes:

scope '(:locale)', constraints: { locale: /nl|fr/ } do      resources :articles, :path => 'newsfeed', only: [:index, :edit, :destroy, :update, :new, :create]      root to: 'languages#select'      get '*path' => redirect('/')  end  

In my application.rb I have

config.i18n.default_locale = :fr  config.i18n.available_locales = [:fr, :nl]  

In welcome page, where the users have to select their language, I have this

<%= link_to "Neederlands", home_path(:locale => 'nl') %> | <%= link_to "Français", home_path(:locale => 'fr') %>  

To sum up, the URLs for the locale=nl will always show *http://localhost:3000/nl/newsfeed but for the default locale fr this is not the case and I need to fix that.

Any idea?

Ruby on Rails: required parameters for model

Posted: 21 Aug 2016 04:47 AM PDT

Rails 5. I have model User and I want field "login" to be obligatory.

What I did:

class User < ApplicationRecord    has_one :cart      def create      User.create(user_params)    end      private    def user_params      params.require(:user).permit(:login)    end  end  

But it doesn't work. I can save new user without login.

irb(main):001:0> user2 = User.create    begin transaction    SQL (1.5ms)  INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", 2016-08-21 11:38:17 UTC], ["updated_at", 2016-08-21 11:38:17 UTC]]    commit transaction    => #<User id: 4, login: nil, created_at: "2016-08-21 11:38:17", updated_at: "2016-08-21 11:38:17">  

How to fix it?

rake db:migrate invalid schema error for role that owns the schema

Posted: 21 Aug 2016 04:39 AM PDT

In my database.yml

  default: &default    adapter: postgresql    encoding: unicode    pool: 5      timeout: 5000    database: postgres    username: website    development:    <<: *default    host: localhost    password: password    schema_search_path: "website_dev"  

In the postgres database as admin user I run

ubuntu=# CREATE USER website WITH PASSWORD 'password';  CREATE ROLE  ubuntu=# CREATE SCHEMA website_dev AUTHORIZATION website;  CREATE SCHEMA  ubuntu=# CREATE SCHEMA website_test AUTHORIZATION website;                                                                                 CREATE SCHEMA  

This should mean the user/role website can create tables in both the schemas website_dev and website_test, however rake db:migrate task fails with the error

ActiveRecord::StatementInvalid: PG::InvalidSchemaName: ERROR:  no schema has been selected to create in  : CREATE TABLE "schema_migrations" ("version" character varying PRIMARY KEY)  

PubSub the connection was interrupted while the page was loadibng error

Posted: 21 Aug 2016 04:51 AM PDT

I have a PubSub subscribed here

ul.questions_list   -if(@questions.empty?)      |no questions available   -else     -@questions.each do|question|       li          =link_to"#{ question.title } ", question_path(question)          p= link_to 'Ask question', new_question_path  = subscribe_to '/questions'  

then goes coffee(in this case console.log gives right data)

$ ->    PrivatePub.subscribe '/questions', (data, channel) ->      question = $.parseJSON(data['question'])      console.log(question.title)      $('.questions_list').append("<li><a href='/questions/#{question.id}'>#{question.title}</a></li>");  

And controller

  def create      @question = Question.new(question_params)      @question.user = current_user      if @question.save        PrivatePub.publish_to '/questions', question: @question.to_json        redirect_to @question, notice: 'Your question successfully created.'      else        render :new      end    end  

I recieve such error

The connection to ws://localhost:9292/faye was interruped while the page was loading.  ...et;t.exports={create:function(t){return **new** n(t)}}}).call(e.function(){return th...)  

I do not understand where Im doing wrong. Would be very grateful for any help

Ruby on Rails difference between cookies[:remember_token] and cookies["remember_token"]

Posted: 21 Aug 2016 04:43 AM PDT

I have trouble undestanding the following situation:

I am logging in and remembering my users by doing the following

class SessionsController < ApplicationController      def create      user=User.find_by(email: params[:session][:email])      if user && user.authenticate(params[:session][:password])        log_in(user)        params[:session][:remember_me]=="1" ? remember(user) : forget(user)        redirect_to user      else        flash.now[:danger]="Invalid email/password combination"        render "new"      end    end  

and

module SessionsHelper        def remember(user)          user.remember          cookies.permanent.signed[:user_id]=user.id          cookies.permanent[:remember_token]=user.remember_token      end  

all of which works fine. The thing that I don't understand though, is that in an integration test I have to use cookies["remember_token"] because in the following situation cookies[:remember_token] will return nil

test "login with remember_me" do      log_in_as(@user)      assert_not_nil cookies["remember_token"]  end  

Why does it return nil here and why does it not do that, if I use it for example as a parameter in a function inside of the Sessionhelper ( for example user.authenticated?(cookies[:remember_token]) )

P.S.: All of the code above comes from the Ruby on Rails Tutorial by Michael Hartl https://www.railstutorial.org/book (chap. 9.3.1)

Distinguisihing normal text from a youtube link Ruby on Rails

Posted: 21 Aug 2016 07:04 AM PDT

Hello all i am making a facebook clone using ruby on rails, I got a post form where i can write text and add a youtube link if i want and it works. However writing a text like "hello world"+ "www.youtube.com/etc" would be output as "hello worldwww.youtube.com/..." If i would just write "hello world" it would make a iframe for a youtube video which isnt correct either.

My application helper

def embed(youtube_url)    youtube_id = youtube_url.split("=").last    content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}")  end  

In my view

<p><%= embed post.content %></p>  

My question is how could i make an if else statement to see if a youtube url is present, if so show the video but hav it on its own "block" and the text separate, if no video dont display the iframe and just the normal text that i write.

Current output:

    <div class="post-content">  Hello World this is a sample text  https://www.youtube.com/watch?v=X3dVpRAmq_8<br>  <p><iframe src="//www.youtube.com/embed/X3dVpRAmq_8"></iframe></p>  </div>  

I want to have it show like

This is a sample text

But a if /else statement, if there is a youtube video present add it but in its own

tag, if no video is present just show the normal content i add

ruby on rails multiple step form

Posted: 21 Aug 2016 05:24 AM PDT

I have been doing some research into using multistep forms for my ruby on rails project, and have come across the wicked gem which seems to tick all the boxes. Upon further investigation, I see it is only good for showing/updating. does anyone know if its possible to use this gem for creating as I want to use the link for my signup process which will show a different set of fields depending on if the user selects they are a customer or a supplier?

How to insert serialized data into database using rails console

Posted: 21 Aug 2016 04:53 AM PDT

I added dynamic form fields to my rails app folowing the tutorial on this link railscasts or youtube and the source code github

creating/updating using forms data works well as expected. however, I get the following error

undefined method `humanize' for :author:Symbol  

when I try viewing the product inserted using console with this command for example

Product.create(product_type_id: 1, name: "refactoring", price: 24.99, properties: {author: "Martin Fowler", page_count: 197, paperback: 1 } )  

examining the database I noticed that the data inserted through the console doesn't get serialized

example data submitted through form:

--- !ruby/hash:ActionController::Parameters  author: Martin Fowle  page_count: '197'  paperback: '1'  

example data submitted through console:

---  :author: Martin Fowle  :page_count: '197'  :paperback: '1'  

How can I get this to work?

I need this because I would also like to be able to update products using data from external sources, like data from APIs.

Simple_form - how to set a class for a wrapper when field is required

Posted: 21 Aug 2016 05:39 AM PDT

Is it possible to set a class, as an example 'field-required' for a input element wrapper? Ideally, i need to generate something like this:

<div class="form-group">    <label class="col-sm-4" for="order_last_name">Last name</label>    <div class="col-sm-8 field-required field-invalid" id="order_last_name">      <input name="order[last_name]"/>    </div>   </div>
Notice that i need to insert field-required and field-invalid to the div containing <input.../>. So i also need to set error_class: to that div

This how i set up the wrapper so far:

config.wrappers :long_input, tag: 'div', class: 'form-group' do |b|    b.use :html5    b.use :label, class: 'col-sm-4 control-label'    b.wrapper tag: 'div', class: "col-sm-8", error_class: 'field-invalid' do |ba|      ba.use :input, class: 'form-control'      ba.use :error, wrap_with: { tag: 'p', class: 'help-block invalid-field-info' }    end  end  

error_class: does nothing when specified with nested wrapper, and how to add field-invalid class when validation fails?

Geokit Rails. Don't know where to begin?

Posted: 21 Aug 2016 02:25 AM PDT

I want to use the geokit gem for my app, but I have no idea where to begin.

So, what I'd like to do is that my users can see if there is anyone around them in the 1 mile range.

The first thing I wanted to do was add a column to my database, but I can't find what type I should use, and in the documentation, it says it's only about MySQL.

class AddIndexToPageLatAndLng < ActiveRecord::Migration      def self.up      add_index  :pages, [:lat, :lng]    end      def self.down      remove_index  :pages, [:lat, :lng]    end  

end

Now, how would I AddFieldsToUsers in Sqlite? Is it an integer or a string?

Also, I'd like to know how to get the current user current address, so that I could use it in my index page.

I'm thinking of something like this:

User.find(:all, :origin=> @user.current_address, :within=>1)  

Using MYSQL views in rails

Posted: 21 Aug 2016 02:09 AM PDT

I want to create a view on MYSQL table and found the gem https://github.com/anykeyh/rails_db_views

but I did not understand how could I use it as I find the documentation not clear. Where should I put this code in my project (which file and directory )

Rails.configure do |config|    config.rails_db_views.views_path += %w( /some/view/path )    config.rails_db_views.views_extension = "*.sql"      config.rails_db_views.functions_path += %w( /some/function/path )    config.rails_db_views.functions_extension = "*.sql"  end  

I would be thankful if anyone told the full steps to use it .

How to install new software onto a GCP flexible environment VM

Posted: 21 Aug 2016 01:15 AM PDT

I have a ruby on rails app running on a Google Cloud Platform VM running on the app engine flexible environment. It looks like it installs most of the software on the VM when I deploy the app with gcloud --project project-name preview app deploy I think it installs rails and other software from reading the temporary dockerfile it creates. It grabs the info for the dockerfile from the app.yaml file (I got this setup from following their tutorials).

This was working fine for me but now I need to install ImageMagick onto the server to manipulate images on the site. Normally you do this by running sudo apt-get install imagemagick from the project directory. When I SSH onto the VM I cant find the project directory so that doesn't work.

I have no idea how to get it to run sudo apt-get install imagemagick each time I make a new deploy to the site so it has the software on the new VM.

As you might be able to tell I'm not very good with the server side of things and want to know what I'm supposed to do to get new software onto the VM the right way so its always there like ruby and rails etc.. are each time I make a new deploy.

How to post authenticity_token?

Posted: 21 Aug 2016 01:56 AM PDT

Now I use arduino sending data to rails in json format. But how to get authenticity_token and send it to rails? Where it should be written ? In json or http header? What the format should be?

If I add

protect_from_forgery :exception => :create  

In the controllers it works fine.But I do not want do disable the CSRF protection. This is my arduino code:

    client.println("POST /players.json HTTP/1.1");      client.println("Host: 192.168.1.3:3000");      client.println("User-Agent: Arduino/1.0");      client.println("csrf-param: authenticity_token");      client.println("csrf-token: V4gTh8yNdz9VMybUXkI6tHxzAHdfk3I+UoiXhxZWK0bkoh8iG5hVJ5sZOjzMAYLlwCwsXQQM102b1hF6TVyYJw==");      client.println("Connection: close");      client.println(lengthInfo);      client.println("Content-Type: application/json");      client.println();      root.printTo(client);  

root.printTo(client) just send son.

I found a similar question:

HTTP request to update rails model from arduino

@Okomikeruko Do you figure out how to send an authenticity token from Arduino?

How to add Combination of uniqueness and add index for two columns in my model?

Posted: 21 Aug 2016 12:44 AM PDT

I have done the below code within my migration file. But it's not working, and also returns errors. I am also using scope.

def change    add_column :load_shortlisted_trucks, :load_id, :integer    add_index :load_shortlisted_trucks, :load_id, name: "load_id"    add_column :load_shortlisted_trucks, :company_truck_type_id, :integer    add_index :load_shortlisted_trucks, :company_truck_type_id, name: "company_id"    add_index :load_shortlisted_trucks, [:company_truck_type_id, :load_id], unique: true  end  

Errors :

== 20160821065543 AddIndexToLoadShortlistedTrucks: migrating ==================  -- add_column(:load_shortlisted_trucks, :load_id, :integer)     -> 0.0017s  -- add_index(:load_shortlisted_trucks, :load_id, {:name=>"load_id"})     -> 0.0545s  -- add_column(:load_shortlisted_trucks, :company_truck_type_id, :integer)     -> 0.0013s  -- add_index(:load_shortlisted_trucks, :company_truck_type_id, {:name=>"company_id"})     -> 0.0061s  -- add_index(:load_shortlisted_trucks, [:company_truck_type_id, :load_id], {:unique=>true})  rake aborted!  StandardError: An error has occurred, this and all later migrations canceled: Index name 'index_load_shortlisted_trucks_on_company_truck_type_id_and_load_id' on table 'load_shortlisted_trucks' is too long; the limit is 63 characters       

Can anyone tell how can I resolve this issue?

Rails 4 - how to add an edit link for a nested resource

Posted: 21 Aug 2016 12:12 AM PDT

I'm trying to figure out nested routes.

I have models called Project and Potential Use. The associations are:

Project

has_many :potential_uses        accepts_nested_attributes_for :potential_uses, reject_if: :all_blank, allow_destroy: true  

Potential Use

belongs_to :project  belongs_to :user  

In my projects show, I'm trying to loop through each potential use.

<% @project.potential_uses.each do |pu| %>        <div class="row">              <p><%= pu.comment %></p>              <strong><%= pu.user.formal_name %></strong>                <%= link_to 'Edit', edit_project_potential_use_path(pu) %>                <p style= 'border-bottom: solid; border-bottom-width: 1px'></p>           </div>          <% end %>  

When i try this edit link, I get an error that says:

No route matches {:action=>"edit", :controller=>"potential_uses", :id=>nil, :project_id=>#<PotentialUse id: 14, comment: "asdf", project_id: 17, created_at: "2016-08-19 01:36:49", updated_at: "2016-08-19 01:36:49", user_id: 1, private_comment: false>} missing required keys: [:id]  

I've tried several different versions of the edit link.

<%= link_to 'Edit', edit_project_potential_use_path(potential_use) %>      <%= link_to 'Edit', edit_project_potential_use_path(project.potential_use) %>  

I can't find a way that works.

My rake routes, shows this for the edit action:

edit_project_potential_use GET       /projects/:project_id/potential_uses/:id/edit(.:format)     potential_uses#edit  

To my eye, this looks like I need to ask for plural references to the resources in the edit link (although it doesnt make sense to me), like so:

<%= link_to 'Edit', edit_projects_potential_uses_path(pu) %>  

That formulation gives this error:

undefined method `edit_projects_potential_uses_path' for #<#<Class:0x007fd4b7431b18>:0x007fd4b7430678>  Did you mean?  edit_project_potential_use_path                 edit_project_potential_use_url  

I can't see how to take this information and use it to write an edit link.

Can anyone see what I've done wrong?

Rails attr_accessible atrribute isn't working isn't working [duplicate]

Posted: 20 Aug 2016 11:23 PM PDT

This question already has an answer here:

I'm doing this tutorial in Rails + Devise and I've stuck my head. There's this:

    # Setup accessible (or protected) attributes for your model       attr_accessible :email, :name, :password, :password_confirmation, :remember_me         validates :email, :presence => true, :uniqueness =>  

I tried to translate it to Rails5 since attr_accesible isn't working Rails5 but seriously...I'm in the corner. What's the proper way to do here to make it work? I tried to define a method with permit parameters but it didn't really work out. I'd be really glad if you could give me a good hint on that!

Stripe charge or plan?

Posted: 21 Aug 2016 12:22 AM PDT

Right now, this is my create action for my charges controller:

def create      # Amount in cents      @amount = 100        # Get the credit card details submitted by the form      customer = Stripe::Customer.create(          :email => params[:email],          :source  => params[:stripeToken]      )        # Create the charge on Stripe's servers - this will charge the user's card      begin        Stripe::Charge.create(            :amount => @amount,            :currency => 'usd',            :customer => customer.id,            :description => 'Example charge custom form'        )        redirect_to root_path          rescue Stripe::CardError => e        flash[:error] = e.message        redirect_to root_path      end        current_user.subscribed = true      current_user.stripe_id = customer.id      current_user.save          flash[:success] = "Thank you for subscribing. Your account has been unlocked."  end  

I want to do something like current_user.end_date = (a month from now). Not actually sure how to do this.

Then I would check if current_user.end_date is in the future every time the individual logs in. If it's not, I make current_user.subscribed = false.

Is this possible, and if so, would you be able to walk me through this because I'm not understanding how to use time too well in rails. Or should I consider doing this as a plan? I wasn't sure because I don't want recurring billing.

1 comment:

  1. Thanks for the valuable Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
    IELTS Coaching in Chennai
    IELTS Online Coaching
    IELTS Coaching in Coimbatore

    ReplyDelete