Sunday, March 20, 2016

change column type to integer rails | Fixed issues

change column type to integer rails | Fixed issues


change column type to integer rails

Posted: 20 Mar 2016 06:33 AM PDT

I have run a migration when trying to change on heroku table column from string to integer: This is my migration:

class ChangePriceTypeInItems < ActiveRecord::Migration    def change      change_column :items, :price, :integer    end  end  

And this is my error: What do I do?

ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "price" cannot be cast automatically to type integer  HINT:  You might need to specify "USING price::integer".  : ALTER TABLE "items" ALTER COLUMN "price" TYPE integer  

How to get rid of additional spaces using redcarpet gem (Ruby on Rails)

Posted: 20 Mar 2016 06:35 AM PDT

I'm trying to write blog using markdown, and decided to install redcarpet gem. Everything looks fine, pygments.rb are doing great job with syntax highlighting, BUT the problem is, whenever I try to put block of code using ``` I get all lines (except the first one) indented by 6 additional spaces. How to get rid of that?

application_helper.rb

module ApplicationHelper    class HTMLwithPygments < Redcarpet::Render::HTML      def block_code(code, language)        Pygments.highlight(code, lexer: language)      end    end      def markdown(content)      renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)      options = {        autolink: true,        no_intra_emphasis: true,        disable_indented_code_blocks: true,        fenced_code_blocks: true,        lax_html_blocks: true,        strikethrough: true,        superscript: true      }      Redcarpet::Markdown.new(renderer, options).render(content).html_safe    end  end  

Post view - show.html.haml

.container    .show.title      = @post.title    .show.header      = @post.header    .show.created_at      = @post.created_at    .show.content      = markdown @post.content  

This is how code looks like in sublime:

code in sublime

This is how rendered post looks like with copy-pasted the same code to post content:

code after copy-paste to a post content

I'm using SublimeText3 with 2 spaces indentation, views are in html.haml format.

This is the exact input of post content:

```ruby  module ApplicationHelper    class HTMLwithPygments < Redcarpet::Render::HTML      def block_code(code, language)        Pygments.highlight(code, lexer: language)      end    end      def markdown(content)      renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)      options = {        autolink: true,        no_intra_emphasis: true,        disable_indented_code_blocks: true,        fenced_code_blocks: true,        lax_html_blocks: true,        strikethrough: true,        superscript: true      }      Redcarpet::Markdown.new(renderer, options).render(content).html_safe    end  end  

Deleting multiple records based on specific conditions in rails 4

Posted: 20 Mar 2016 06:40 AM PDT

Im trying to create a button that will delete all expired records from the database, but not sure exactly as to how to achieve this. I think I got the controller part set up correctly, but im not sure what to put in the routes and the code for the button itself to delete the desired records. This is what I have in my controller:

      def delete_expired          @expired_sales = Sale.where('offer_end <= ?', Date.today)          @expired_sales.destroy_all          redirect_to root_path, notice: 'Successfully Deleted Sales.'        end  

How to group_by this array of hashs (Enumerable) [Ruby, Rails]

Posted: 20 Mar 2016 06:55 AM PDT

I have an array (@items) of hashs with this structure:

@items:

{'item' => item, 'stickers' => stickers}  ...  

And the item is an ActiveRecord with the attr I want to group_by: csgo_type.

My code:

<% @items.group_by { |d| d['item'][:csgo_type] }.each do |a| %>      <%= render partial: 'item', locals: {a: a} %>  <% end %>  

But this doesnt group at all.

I'm looking for a result like this:

[ { :csgo_type => #ActiveRecord(csgo_type 1), :items => [array of some @items of this type] }, {...} ...]

Solution:

<% @items.group_by { |d| d['item'].csgo_type }.each do |a,b| %>      === <%= a.name %>      <% b.each do |cada| %>          <%= render partial: 'item', locals: {cada: cada, i: 1} %>      <% end %>  <% end %>  

Validate that option is selected before progressing

Posted: 20 Mar 2016 06:14 AM PDT

I have the following options within a form:

<%= form_for @user  do |f| %>              <%= render 'shared/errors', object: @user %>              <div class="form-group">                  </br>                  <%= f.radio_button :activity, 'Music' %>                   <%= f.label :activity, 'Music', value: 1, required: true%><br><br>                  <%= f.radio_button :activity, 'Sport' %>                  <%= f.label :activity, 'Sport', value: 2, required: true %><br><br>              </div>  <%= f.submit 'Submit', class: 'btn btn-primary btn-lg' %>  <% end %>  

I want to require the user to select one of these options before progressing. I have entered required: true but it doesn't seem to validate what I need it to. Do i need some sort of validation in my model?

rails undefined method `id' for nil:NilClass with belongs to relationship

Posted: 20 Mar 2016 06:16 AM PDT

This is my item model:

class Item < ActiveRecord::Base      has_many :props  end  

This is my prop model ( porp is short from property)

class Prop < ActiveRecord::Base    belongs_to :item  end  

I have this problem. When I create prop I require item_id. But if there is no item with this id I will get an error here:

<%= @prop.item.id %>        <%= @prop.item.name %>  

What do I do?

UPD:I can check its existence like <%= @prop.item.try(:name) %> What are my other options?

POST 500 (Internal Server Error) using Ajax, React and Rails

Posted: 20 Mar 2016 06:12 AM PDT

I'm just taking a step to use Ajax so I may missed something very important. Instead of having the page to refresh, I now want to use ajax. I'm testing a small code but the browser console says:

POST 500 (Internal Server Error)

Routes:

post 'to/test' => 'foo#bar'  

.jsx:

test(e){      $.ajax({        url: 'to/test',        type: 'POST',      });  },  

foo_controller.rb:

def bar   u = User.last   u.age = 99   u.save  end  

Looking at my rails console, the user's age was set to 99. Anything I've missed in my ajax learning?

Rails one to many confusion

Posted: 20 Mar 2016 05:53 AM PDT

I'm trying to wrap my head around associations in Rails. I come from iOS development background. I have a basic one-to-many working I think but I feel like I'm doing it wrong, so I'm asking on here to make sure.

So far, I have

user.rb

class User < ApplicationRecord    has_many :cats  end  

cat.rb

class Cat < ApplicationRecord    belongs_to :user, optional: true  end  

I have generated my migration like so:

rails generate migration add_user_to_cats user:references  

Migration file

class AddUserToCats < ActiveRecord::Migration[5.0]    def change      add_reference :cats, :user, foreign_key: true    end  end  

Route.rb

Rails.application.routes.draw do    resources :cats    resources :users    get '/users/:id/cats', to: 'users#user_cats'    get '/adopt/:id', to: 'users#adopt'  end  

When user go to localhost:3000/users/1/cats for example, it executes my controller method:

def user_cats    cats = Cat.where(user_id: params[:id])    render json: cats  end  

Question

First of all, is this the correct way to fetch all cats for a user ?

It just doesn't feel right...

Coming from an iOS development background and using CoreData, I am used to being able to do something like:

cats = user.cats  

and

user = cat.owner  

but my initial encounter with Ruby on Rails and ActiveRecords doesn't seem to suggest so.

Is it possible for Rails to do what is shown above?

Alchemy CMS: Create element that contains list of elements

Posted: 20 Mar 2016 05:39 AM PDT

I'd like to create an element which can contain a list of items, where each item can have more than one essences.

For example: The user should be able to add a "page listing" as content element. For each page item he should be able to upload a small image, a short description and a link. Because the list needs to be wrapped with an UL tag, I can't simply ask him to add a lot of elements.

Other example: The user should be able to add a "team listing" as content element. Each member having a photo, a name, a job description and an email address. Same problem here: I'd like to have the team members wrapped within an DL tag.

Is there some way of releasing elements which can contain elements?

Some kind like: (just an example, might contain bugs)

- name: my_list_element    contents:    - name: list_style      type: EssenceSelect    - name: items      type: Element ???      elements: [my_item_element]      settings:        deletable: true    available_contents:    - name: items      type: Element ???      elements: [my_item_element]      settings:        deletable: true    - name: my_item_element    contents:    - name: image      type: EssencePicture    - name: headline      type: EssenceText      ...  

The inner item uses the default editor for pictures or text essences.

If someone knows a way how to realize this it would be very great, because it's the last puzzle part which is missing in order to use alchemy CMS :(

Thank you in advance

Preventing SQL Injection in Rails while using Javascript Query Builder

Posted: 20 Mar 2016 05:08 AM PDT

I would like to use jQuery query builder as a tool in a multi-user app: http://mistic100.github.io/jQuery-QueryBuilder/

I understand using such an tool could potentially carry great risks for SQL injection if not setup properly.

I am aware of the traditional methods of preventing against SQL injection (i.e. hardcoding the WHERE statement rather than inserting user-inputed strings directly in), but in this case that would prove to be a bit more difficult given how dynamic and flexible we are trying to keep things.

I am wondering if there are any easy ways to setup a secure process while using something like this query builder. The main concern is one user being able to access and/or modify another user's records (I am not as concerned about them messing with their own records, but they're all in the same database).

One idea I had is doing a find and replace for any problematic words (i.e. DROP, etc), but I understand this would place limitations on user-input (i.e. if they wanted to search records that matched "He dropped the ball")...and also is perhaps not foolproof.

Are there any other methods that might work, short of having to code in some complicated algorithm to generate SQL code server side?

How do I achieve single sign on and data sharing across 2 rails apps?

Posted: 20 Mar 2016 04:46 AM PDT

I am looking to set up 2 rails apps (with the same tld) which have single sign on and share some user data. If I have railsapp.com I will have the second app set up as otherapp.railsapp.com or railsapp.com/otherapp. I will most likely have railsapp.com handle registration/login etc (open to suggestion if this is not the best solution).

So lets say I sign up and upload an avatar and start accumulating user points on the main-app, I can then browse to the other-app and my profile there has the correct avatar and points total. is there an easy way to achieve this? Do the available SSO solutions create the user in the second app with the same user ID? if not, how are they tied together? (ie how can I query the other app for information I would like to be shared across the 2 - user points and avatar) I was initially looking at sharing a database or at least the user table between the 2 apps, but I can't help thinking there must be an easier solution?

Rails 5.0.0beta3: ActionController::InvalidAuthenticityToken in development

Posted: 20 Mar 2016 06:04 AM PDT

I have just started a simple app with a couple of forms on Rails 5.0.0beta3.

In development, using http://localhost:3000 on Safari or Chrome to access the app, if I fill a form and submit it I always get an ActionController::InvalidAuthenticityToken error. However, if I reload the page before filling and submitting it then it works fine.

The app uses the defaults:

  • protect_from_forgery with: :exception in ApplicationController,
  • <%= csrf_meta_tags %> in html header through application layout,
  • development environment as created by rails.

Example:

<%= form_for @node, url: admin_book_nodes_url, as: :node do |form| %>    <%= render "form", f: form %>    <p><%= form.submit %> or <%= link_to "Cancel", admin_book_nodes_path %></p>  <% end %>  

Log:

Started POST "/admin/book/nodes" for ::1 at 2016-03-20 11:54:31 +0000  Processing by Admin::Book::NodesController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"/G5pF6hSPx0Vf21Fi0FCh+VlOcHY4w8C5lmHmwr3NQRjfXUP9/xboybeV3tevmyTyHcwSX8LplU/HgZVGDbGlw==", "node"=>{"parent_id"=>"1", "position"=>"1", "title"=>"lkjlkj", "description"=>"lkjlj", "published"=>"0", "content"=>"lkjlkj"}, "commit"=>"Create node"}  Can't verify CSRF token authenticity  Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)  

It works fine if I disable per form CSRF tokens in the controller (self.per_form_csrf_tokens = false) so my issue is really at that level.

The session does not seem to be reset at any point.

Interestingly, when the form is first loaded, the authenticity token in the header's menage tag is different from the token in the form. The meta tag is also at the bottom of the header's tags. When I then reload the tokens are the same in both the meta tag and the form, and the meta tag is at the top of the header's tags.

why mock data while testing?

Posted: 20 Mar 2016 05:29 AM PDT

I'm trying to learn some testing, and stumbled upon mocking and stubbing. I actually think I can get the difference here, point I can't think of any reason i should use mocking in the first place. Lets look at the example code from Mocha gem documentation:

require 'test/unit'  require 'mocha/test_unit'    class MiscExampleTest < Test::Unit::TestCase     test "mocking_an_instance_method_on_a_real_object" do        person = Person.new        person.expects(:save).returns(true)        assert person.save       end  

I dont understand the reason behind this line:

person.expects(:save).returns(true)  

Whether I use it or not, the output is completely the same: the test passes. I can feel that it has something to do with telling the object/class how to behave, but how is that testing if we first tell the object to return true and then check if it returns true? It always will, we told it to. Isn't it pointless?

How to render error messages for a json form in Rails

Posted: 20 Mar 2016 02:36 AM PDT

I'm trying to display error messages for a failed from submit on an ajax form. I haven't gone down the path of ajax forms before and cant find a solid upto date guide on how to get error messages to show when the form fails to save the data for whatever reason.

I have format.json { render :json => { :errors => @key.errors.full_messages }, :status => 422 } in the controller fo a failed form submit as you can see below. But I have no idea on what JS or coffeescript to have so the error messages are displayed.

category_item_keys controller

def new     @guide      = Guide.friendly.find params[:guide_id]     @category   = Category.friendly.find params[:category_id]     @key        = @category.category_item_keys.new  end      def create        @guide      = Guide.friendly.find params[:guide_id]      @key        = @category.category_item_keys.new key_params      @category   = Category.friendly.find params[:category_id]        if @key.save        CategoryItemKey.find(@key.id).update(submitted_by: current_user.id, approved_by: current_user.id, guide_id: @guide.id)        respond_to do |format|         format.html {  redirect_to new_guide_category_category_item_key_path(@guide, @category)                flash[:success] = "Key added successfully!"  }         format.json { render :json }       format.js          end     else      respond_to do |format|        format.html {  render 'new' }        format.json { render :json => { :errors => @key.errors.full_messages }, :status => 422 }      format.js      end   end    end    def key_params     params.require(:category_item_key).permit(:name, :key_type)  end  

new.html.erb

<%= form_for([@guide, @category, @key], url: guide_category_category_item_keys_path, remote: true, :authenticity_token => true) do |f| %>     <%= render 'shared/error_messages', object: f.object %>       <%= f.label :name, "Key name" %>     <%= f.text_field :name %>       <%= f.select :key_type, [['Stat', 1], ['Attribute', 2], ['Image', 3], ['Text', 4]] %>       <%= f.submit "Next"  %>  <% end %>  

category_item_key.coffee

# No idea what is needed in here  

I've read over all the posts I can find to see what needs to go in category_item_key.coffee but they are all 3-5 years old and just don't work. I'm sure its not that complicated but I don't know much about JS to get it working.

wicked_pdf gem + Highcharts

Posted: 20 Mar 2016 02:28 AM PDT

I read some answers, but didnt solve my problem.

Html charts works good, but when I export to PDF with wicked_pdf charts doesnt show.

I set chart options :

 plotOptions: {        series: {          enableMouseTracking: false,          shadow: false,           animation: false        }      },  

And tried giving javascript delay.

I tried including and not including in my layout the jquery and/or highcharts js files again according to some posts I read.

But nothing is working for me , my wkhtmltopdf library version is :

wkhtmltopdf 0.12.2.1 (with patched qt)  

All answers I read are 2+ years old so maybe someone can help me with a newer method.

Why this route goes to the show action

Posted: 20 Mar 2016 02:59 AM PDT

This request goes to SHOW action in Webservices controller..

 Reuest : webservices/getsomething&ids=1  

This

 Reuest : webservices/getsomething  

goes where I wanted at getsomething action ...
This is my route.rb :

  resources :webservices do      collection do        get 'getsomething'      end    end  

rake routes :

  getsomething_webservices GET    /webservices/getsomething(.:format)              webservices#getsomething  

and still rails go in show action ???

I can't do heroku push. ruby on rails

Posted: 20 Mar 2016 02:22 AM PDT

I did git push heroku master then I got error below

! [remote rejected] master -> master (pre-receive hook declined)      error: failed to push some refs to 'https://git.example.com  

So I did heroku logs --tail to find out the problems then I got below

enable Logplex by exmaple@mail.com  Release v2 created by example@mail.com   Slug compilation failed: failed to compile Ruby  

I don't know how to fix this issue and push heroku well. need your help!

how to manage users by an admin in ruby on rails

Posted: 20 Mar 2016 03:08 AM PDT

how can I manage and edit other users profiles as an admin since I have one model and controller (users) ?

I tried to add a new action called updateusers

def updateusers      @other_user=User.find(params[:id])      if @other_user.update_attributes(otherusers_params)               redirect_to '/'       else              redirect_to '/manage'     end  end   

the problem here :it is updating my admin user with the other_user's data

stack trace

    Started GET "/manage" for ::1 at 2016-03-19 21:06:08 +0300 Processing by       UsersController#manage as HTML User Load (1.0ms) SELECT "users".* FROM   "users" Rendered users/manage.html.erb within layouts/application (5.0ms) User   Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1   [["id", 1]] Completed 200 OK in 53ms (Views: 51.0ms | ActiveRecord: 1.0ms)          'Started GET "/users/10" for ::1 at 2016-03-19 21:06:10 +0300 Processing by   UsersController#show as HTML Parameters: {"id"=>"10"} User Load (0.0ms) SELECT   "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] Rendered   users/show.html.erb within layouts/application (0.0ms) User Load (0.0ms) SELECT   "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200   OK in 37ms (Views: 36.0ms | ActiveRecord: 0.0ms)          Started GET "/editusers/10" for ::1 at 2016-03-19 21:06:11 +0300 Processing   by UsersController#editusers as HTML Parameters: {"id"=>"10"} User Load (0.0ms)   SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]]   Rendered users/editusers.html.erb within layouts/application (4.0ms) User Load   (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]   Completed 200 OK in 41ms (Views: 39.0ms | ActiveRecord: 1.0ms)          Started PATCH "/users/10" for ::1 at 2016-03-19 21:06:15 +0300 Processing by   UsersController#update as HTML Parameters: {"utf8"=>"✓",   "authenticity_token"=>"6M1TGLQUEhiezCCg9/rT5IofdroMiQ0sm+bYcihgGDxTjDdFGU2Riou2p‌​  cRk5ncjCtFDGwfBj17Uq7gc0u329w==", "user"=>{"first_name"=>"g", "last_name"=>"g",   "email"=>"g@g.g", "role"=>"editor", "image"=>"pic.png", "admins"=>""},   "other"=>"update", "id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users"   WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Unpermitted parameters: role, admins          (0.0ms) begin transaction SQL (1.0ms) UPDATE "users" SET "first_name" = ?,   "last_name" = ?, "email" = ?, "updated_at" = ? WHERE "users"."id" = ?   [["first_name", "g"], ["last_name", "g"], ["email", "g@g.g"], ["updated_at",   "2016-03-19 18:06:15.488284"], ["id", 1]] (47.0ms) commit transaction Redirected   to localhost:8080/profile Completed 302 Found in 54ms (ActiveRecord: 48.0ms)  

Unable to trigger action to controller with websocket-rails gem

Posted: 20 Mar 2016 01:40 AM PDT

I've created a new empty Rails 4.2 app. Then added just websocket-rails gem. Followed the instructions for installing and configuring it at https://github.com/websocket-rails/websocket-rails. But it just doesn't work.

It doesn't work neither in standalone mode nor otherwise (I want to run it in a standalone mode). There're no errors when I start websocket_server. There're no errors in log/websocket_rails.log and log/websocket_rails_server.log. When I do trigger from the dispatcher, nothing happens, just websocket_rails.log shows that 'Connection opened' and after several secs 'Connection closed'. Redis server is running and I can connect to it via rails console.

You could find the app source here https://github.com/poyzn/websocket-rails-test-app.

Trying to run it in development, rvm 1.26.11, ruby 2.1.5, rails 4.2, redis server 3.0.4

Rails 5 get users_path(10) test doesn't fail even no "show" method defined in controller

Posted: 20 Mar 2016 02:21 AM PDT

Me gain, yes. Got a weird problem. This test should fail but it isn't.

Using Rails 5 --api only.

Got a UsersController like so:

class UsersController < ApplicationController    def index      users = User.all      render json: users    end  end  

Test file:

require 'test_helper'    class UsersControllerTest < ActionDispatch::IntegrationTest    test "users should return list of users" do      get users_path      assert_response :success        assert_not response.body.empty?    end      test "show valid id should return user json" do      get users_path(10)      assert_response :success    end  end  

Routes.rb defined like this:

Rails.application.routes.draw do    resources :cats    resources :users  end  

The console output:

Running via Spring preloader in process 4176  Run options: --seed 28710    # Running:    ........    Finished in 0.100764s, 79.3937 runs/s, 138.9390 assertions/s.    8 runs, 14 assertions, 0 failures, 0 errors, 0 skips  

Why is the test not reporting error when the controller clearly has no show method defined ?

Going to my browser localhost:3000/users/10 returns JSON saying "show" method does not exists.

Any ideas?

Rails: Assigning another user to an excisting entry (associations)

Posted: 20 Mar 2016 01:08 AM PDT

I have 2 models in my project. 1 is Users and 1 is courses. A user has many courses and courses has many users. The main problem is that I can't figure out how to assign users to courses without creating a new course.

user = User.first   course = Course.new(title:"course01")  

My output would then be something like

Course id: 2, title: "course01", created_at: "2016-03-20 07:05:23",              updated_at: "2016-03-20 07:05:23", user_id: 1>  

Now I can't figure out how to add another user to this same course.

user = User.second  ?  

Rails 4 not able to get the actual website url stored in the database

Posted: 20 Mar 2016 12:27 AM PDT

I have a string field in my User table where I store the user's github website url. Now, I am trying to show the link on the user's profile page. Instead of getting 'https://www.github.com'(example link)...I am getting "localhost/users/www.github.com". I tried it the following way :-

<% if @user.github? %>      <a href="<%= "#{@user.github}" %>"><i class="fa fa-github-alt"></i></a>  <% end %>  

On clicking the link, I get localhost/users/www.github.com instead of just www.github.com. How can this be done correctly ?

Why is the Farday request not picking up the change in path?

Posted: 20 Mar 2016 12:09 AM PDT

I'm doing an exploratory code reading of a gem....If I change this line of code in the airbrake api gem to:

def account_path    "#{protocol}://#{@account}.airbrake.io/api/v4"  end  

and change this line to:

fixture_request :get, "http://myapp.airbrake.io/api/v4/projects/#{PROJECT_ID}/groups/#{GROUP_ID}/notices?key=abcdefg123456&page=1", 'notices.json'  

and change this line (and change the corresponding function parameter of @client.notices to accomodate the extra parameters, not showing here for brevity) to:

  it "finds all error notices" do      notices = @client.notices(@project_id, @group_id)      expect(notices.size).to eq(2)    end  

I still get this error:

FakeWeb::NetConnectNotAllowedError:         Real HTTP connections are disabled. Unregistered request: GET http://myapp.airbrake.io/projects/1/groups/1696170/notices?key=abcdefg123456&page=1  

Why does Faraday not seem to pick up the /api/v4 part of the path? I have a feeling the issue is in the request method here...

Rails 5: how to use $(document).ready() with turbo-links

Posted: 19 Mar 2016 11:15 PM PDT

Turbolinks prevents normal $(document).ready() events from firing on all page visits besides the initial load, as discussed here and here. None of the solutions in the linked answers work with Rails 5, though. How can I run code on each page visit like in prior versions?

Rails: Allow users only to get points only once. (Prevent users from refreshing page and get points again)

Posted: 19 Mar 2016 11:18 PM PDT

I am creating a course system in rails and I want to award users points for completing a certain task but I want to avoid that the users can refresh the page and get the points again.

My controller looks like this:

def beginnerscourse_08c     @user = current_user     @completion = "100%"     @user.increment(:tradepoints,  100)     @user.save  end  

What is the easiest way to make a boolean or similar system that checks if the user was already awarded theses points and if not reward them.

Why aren't my scss files communicating with each other? [duplicate]

Posted: 19 Mar 2016 10:43 PM PDT

This question is an exact duplicate of:

I'm having trouble with variables in one SCSS file not loading into another. I made a previous post here What's causing this SASS::Syntax error? regarding the issue and decided to just make a new post all together as I've figured out a little more about the issue.

To try eliminating the problem I replaced the variable

$color-3

with the hex code of the color I wanted to display and got the same undefined variable error with the next color variable on the list. I replaced all the color variables and I got the error once again with the font variable further down the file.

All of these variables are in the file

"_variables.scss"

The paths to these files are

vendor > assets > stylesheets > spree > backend > spree_admin.scss

vendor > assets > stylesheets > spree > backend > spree > _bootstrap_custom.scss

vendor > assets > stylesheets > spree > backend > spree > globals > _variables.scss

The "spree_admin.scss" is the file that loads all the stylesheets for the backend and looks like this.

@import 'bourbon';    @import 'spree/backend/globals/functions';  /*@import 'spree/backend/globals/variables_override';*/  @import 'spree/backend/globals/variables';    @import 'bootstrap_custom';  @import 'solidus_admin/bootstrap/bootstrap';    @import 'spree/backend/globals/mixins/caret';    @import 'spree/backend/shared/skeleton';  @import 'spree/backend/shared/typography';  @import 'spree/backend/shared/tables';  @import 'spree/backend/shared/icons';  @import 'spree/backend/shared/forms';  @import 'spree/backend/shared/layout';    //there's a lot more than this but you get the picture  

I also tried adding the underscore before the names and the SCSS file extension to the end of the files but that still didn't make a difference. As I said in the original post, everything was fine before I went to bed. I was clicking all the links making sure everything looked the way I wanted it to look. Yesterday when I woke up I went to work on it some more but after I started the rails server and went to localhost:3000 in the browser I got the undefined variable error. For some reason the "_bootstrap_custom.scss" file isn't reading the variables of the "_variables.scss" file. There's other changes I made to other files that I know are picking up on those variables, so they're being read in, it just doesn't communicate with the bootstrap file for some reason. any idea why?

Devise Registration form is still creating a user despite Stripe not being valid RUBY

Posted: 19 Mar 2016 10:22 PM PDT

I am using Devise to manage Users and am using Stripe to set up 3 seperate subscription plans. However, when the Stripe fields are empty or invalid, it will flash an error screen and still create a new User except without a Plan ID

No such token: undefined  

The registration controller looks like this.

class Users::RegistrationsController < Devise::RegistrationsController    before_filter :select_plan, only: :new      def create      super do |resource|        if params[:plan]          resource.plan_id = params[:plan]          if resource.plan_id == 4 || resource.plan_id == 5 || resource.plan_id == 6            resource.save_with_payment          else            resource.save          end        end      end    end      private        def select_plan        unless params[:plan] && (params[:plan] == '4' || params[:plan] == '5' || params[:plan] == '6')        flash[:notice] = "Please select a membership plan to sign up."        redirect_to root_url      end      end  end  

The following is the model I am using for my User.

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      belongs_to :plan    attr_accessor :stripe_card_token      def save_with_payment      if valid?        customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)        self.stripe_customer_token = customer.id        save!      else        redirect_to root_url        flash[:Danger] = "There was an error with processing your payment. Please try again."      end    end    end  

Hearing in Rails Syntax Error

Posted: 19 Mar 2016 10:06 PM PDT

New to Rails, trying to add a favorites, using hearts on posts in my app and dont know why I'm getting this sytax error. Have followed the tutorial step by step.Is this somethong obvious ?

/Users/leehumphreys/Desktop/with hearts favorites/app/views/rooms/show.html.erb:292: unterminated string meets end of file /Users/leehumphreys/Desktop/with hearts favorites/app/views/rooms/show.html.erb:292: syntax error, unexpected end-of-input, expecting ')'

 <% @rooms.each do |room| %>    <%= room.title %>    <%= div_for room do %>       render "hearts/button", room: room       <% end %>    <% end %  

Actually getting the error at <% @rooms.each do |room| %>

Specific SoundCloud songs do not load artwork and prevent functions of my web app to crash?

Posted: 19 Mar 2016 08:59 PM PDT

I am building a web app of which theres is a function that renders a queue of SoundCloud tracks. Theres is a compiled list of SoundCloud IDs, on click it redirects to home and appends those IDs into the user's queue.

I am noticing specific SoundCloud tracks that prevent this process from occurring, causing the reload to be incomplete. When I manually reload, most of the tracks are there, however specific ones are missing their artwork. They can still be played manually on click. I have noticed that if I remove the IDs with "missing artwork" the queue loads fine.

All ID's are valid, I am not getting a 404 on any requests. The Heroku logs do not show anything unusual, they show a 200 on the requests to create the queue. There is no SoundCloud documentation on this.

I am starting to think it is a SoundCloud error, but I would like to know if anyone has seen this or if there is a solution.

Link to web app: www.songtrast.com

Cannot send email with paramter(id) to my domain's email

Posted: 20 Mar 2016 01:21 AM PDT

I have a domain which I have purchased with Godaddy. I have setup Office 365 email with this domain so that my app or other people could send email by using this domain email.

Right now, I am able to send all email to this domain just fine. But when I try to test to put some parameter(id) onto the address, the email is failed to be sent. I need to be able to make this work as I need to use this domain email for my rails app.

This is example of email address with the id that i am trying to send to: support+296@rentlord.info

And this is the error that I received:

enter image description here

I have tried this with my gmail and gmail completely ignore the "+" sign and the parameter that I supplied and send/receive the email just fine. But when I tried it on my domain, it failed to be sent. Do I need to setup something?

Please help! Thanks!

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete