Monday, March 28, 2016

Rails: Prevent id conflict with a method | Fixed issues

Rails: Prevent id conflict with a method | Fixed issues


Rails: Prevent id conflict with a method

Posted: 28 Mar 2016 06:59 AM PDT

I am using string as id in routes (e.g. resource/:id ) but id can also be 'new' (a method in my Controller) which rather than showing the resource with id=new, directs to create new resource. How can I restrict users from choosing id=new while creating new resource?

Failure in Chapter 9 of Rails Tutorial:

Posted: 28 Mar 2016 07:00 AM PDT

After running the test suite, I get the resulting failure:

UsersIndexTest#test_index_as_admin_including_pagination_and_delete_links [/home/ubuntu/workspace/sample_app/test/integration/users_index_test.rb:19]:  <delete> expected but was  <User 19>..  Expected 0 to be >= 1.  

I have been trying to work this out for a few hours now and am pulling my hair out. This is the file:

users_index_test.rb:

require 'test_helper'    class UsersIndexTest < ActionDispatch::IntegrationTest      def setup      @admin     = users(:michael)      @non_admin = users(:archer)    end      test "index as admin including pagination and delete links" do      log_in_as(@admin)      get users_path      assert_template 'users/index'      assert_select 'div.pagination'      first_page_of_users = User.paginate(page: 1)      first_page_of_users.each do |user|        assert_select 'a[href=?]', user_path(user), text: user.name        unless user == @admin          assert_select 'a[href=?]', user_path(user), text: 'delete'        end      end      assert_difference 'User.count', -1 do        delete user_path(@non_admin)      end    end      test "index as non-admin" do      log_in_as(@non_admin)      get users_path      assert_select 'a', text: 'delete', count: 0    end  end  

Mongoid paperclip ActionController::RoutingError (No route matches [GET]

Posted: 28 Mar 2016 06:44 AM PDT

I have a view where I can create, edit an Room and I can chose a photo for that room when I chose the photo and click the update button I get an error that says:

ActionController::RoutingError (No route matches [GET] "/images/localhost/photos/images/56f9/2fae/23fb/c028/d600/0003/original/large3.jpg"):  

Here class model :

class Room    include Mongoid::Document    validates :listing_name, length: {maximum: 50}, presence: true    field :home_type, type: String    field :room_type, type: String    embeds_many :photos    belongs_to :user  end    class Photo    include Mongoid::Document    include Mongoid::Paperclip    embedded_in :room, :inverse_of => :photos    has_mongoid_attached_file :image,        :styles => {        :original => ['1920x1680>', :jpg],        :small    => ['100x100#',   :jpg],        :medium   => ['250x250',    :jpg],        :large    => ['500x500>',   :jpg]      },      :convert_options => { :all => '-background white -flatten +matte' }       validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end    class RoomsController < ApplicationController      def create      @room = current_user.rooms.build(room_params)      if @room.save        if params[:images]          params[:images].each do |image|            @room.photos.create(image: image)          end        end          @photos = @room.photos        redirect_to edit_room_path (@room), notice: "Saved..."      else        render :new      end        end  end  

Here Route

  resources :rooms    resources :posts    resources :comments    resources :photos      resources :rooms do      resources :reservations, only: [:create]    end      get '/preload' => 'reservations#preload'  

Anybody help me please, whats' wrong my source code :-( ...??

rails pass array link_to

Posted: 28 Mar 2016 06:40 AM PDT

I have a link

link_to 'To basket',order_items_path(order_item:{product_id:[31,32,36]})  

want to send array of params to contoller but have received

Unpermitted parameter

   {"order_item"=>{"product_id"=>["31", "32", "36"]}, "controller"=>"order_items", "action"=>"create"}  "------"    Order Load (0.3ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."id" = $1 LIMIT 1  [["id", 10]]  Unpermitted parameter: product_id  

but i have it

def order_item_params     params.require(:order_item).permit(:quantity, :product_id,:size)  end  

So my question is how to correctly send array of params?

Railstutorial By michael hartl (3rd ed.) chp.10 ex 2 - Show users only when activated

Posted: 28 Mar 2016 06:40 AM PDT

I am working on the railstutorial by michael hartl (3rd edition) exercise 2

There are two small parts in this exercise. First one is a rather easy one (needed to change a FILL IN with TRUE), also the second one should be rather easy, but I am getting an error:

Explanation: A user wants to access an other user's profile page. When this account is not yet activated the user that wanted to access, gets redirected to the root page (easy right?)

The code that I know should do this job:

(app/controllers/users_controller.rb)  def show    @user = User.find_by_id(params[:id])    redirect_to root_url and return unless @user.activated?  end  

(small note: originally the book uses @user = User.find(), I have changed this to User.find_by_id(), because there was an error raised when navigating to an unactivated users page,
what broke the code and the second line would not run, this fixed that )

There are 3 other controller files where I have used the "activated?" method, without any errors whatsoever. But in this occassion I get: undefined method `activated?' for nil:NilClass when visiting an unactivated user's page

Console:

Processing by UsersController#show as HTML  Parameters: {"id"=>"101"}  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?       LIMIT 1  [["id", 101]]  Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.2ms)    NoMethodError (undefined method `activated?' for nil:NilClass):  app/controllers/users_controller.rb:12:in `show'  

Its weird because this is the correct usage. It's shown so in the source code on the github of michael hartl, and I have seen this in other questions regarding this exercise (no duplicate here, the ones I found where about integration tests)
The user is in the database, that I know, because when I try to login I get the message as should: "this user account is not activated yet"

So my question here. What causes the undefined method error when in other controller files I can just use the method, and what is the fix to redirect the user properly, because as far as I know this is the right solution?

If there are more files and/or info needed please let me know

Otherwise I really would like to know the answer, thanks in advance!!

Digital ocean droplet running rails application getting compromised

Posted: 28 Mar 2016 06:29 AM PDT

I was running my rails application on a digital ocean droplet with Ubuntu 14.04. Within days of launch, my droplet got hacked. I had taken care of the following things while setting up the droplet. But still the security had been compromised.

1) No root password. I had set up the root user with ssh key 2) The rails application is hosted in a private repo. So not even the IP of the machine was exposed. 3) Changed the default port of rails app.

I know the above configurations are basic but it usually gets the job done for me.

I setup a new droplet after the droplet was compromised. Again, within days, the new droplet was also compromised. So there is definitely a security hole in my setup.

To give a background about the rails application, it is an app that uses Twilio voice APIs , MySQL as the DB, unicorn as the app server, sidekiq and redis for background processing.

I still have console access to the latest compromised droplet. While looking for clues in the compromised droplet and noticed some rogue ssh key entries in authorized_keys file. I could not find anything else out of the ordinary or how the authorized_keys file got new entries.

How should I be debugging this problem ?

Stripe: received unknown parameter: fingerprint

Posted: 28 Mar 2016 06:55 AM PDT

In my tests I received error:

Failure/Error: stripeToken: stripe_helper.generate_card_token,  Stripe::InvalidRequestError:     Received unknown parameter: fingerprint  

This is my code:

let(:stripe_helper) { StripeMock.create_test_helper }  let(:payment_params) do   { .., stripeToken: stripe_helper.generate_card_token }  end  

What I am doing wrong?

Remove object from array without deleting it from database

Posted: 28 Mar 2016 06:43 AM PDT

I'm having an issue where I just need to remove the duplicates from 2 array of active record objects. The only thing is it is removing it from the database only and I just need it removed from the array in this case. I followed this Remove object from an array of objects and also tried a few other things and they were able to remove it from memory and explicitly remove it from array and not the database but I'm not able to replicate it. Any suggestions would be great. Thanks all!

company_links       = CompanyLinkType.where(company_id: company_ids, contact_linktype_id: 3)  other_company_links = CompanyLink.where(company_id: company_ids, link_type: 'Twitter')      company_links.each do |company_link|    other_company_links.each do |other_company_link|      # checks if id and url match, need to remove obj from company_link array      if other_company_link.company_id == company_link.company_id && other_company_link.url == company_link.contact_link_url        company_link.delete        Rails.logger.info"+++++++++DELETED++++++++++"      end    end  end  

How to make Act_as_votable to work with json

Posted: 28 Mar 2016 06:24 AM PDT

i am using act_as_votable in my micropost conrtoller like this

def upvote      @micropost = Micropost.find(params[:id])      @micropost.liked_by current_user      respond_to do |format|          format.html {redirect_to :back }          format.json { render json: { count: @micropost.get_upvote.size } }      end    end    def downvote      @micropost = Micropost.find(params[:id])      @micropost.downvote_from current_user      respond_to do |format|          format.html {redirect_to :back }          format.json { render json: { count: @micropost.get_upvote.size } }      end  end  

and in my micropost view i have it like this

 <%= link_to like_micropost_path(micropost), method: :get, class: "waves-effect waves-light btn vote", remote: true, data: { type: :json }  do %>   <span class="fa fa-thumbs-up icon"></span><%= "#{micropost.get_upvotes.size}" %>   Upvote     <% end %>     <%= link_to dislike_micropost_path(micropost), method: :get, class: " waves-effect waves-light btn vote", remote: true, data: { type: :json }  do %>   <span class="fa fa-thumbs-down icon"></span><%= "#{micropost.get_downvotes.size}" %>   downvote     <% end %>  

so when ever i vote i get this error in console

NoMethodError (undefined method `get_upvote' for #<Micropost:0x007f75549858e8>):  

app/controllers/microposts_controller.rb:35:in block (2 levels) in downvote' app/controllers/microposts_controller.rb:33:indownvote'

but after refreshing the results appers. how can i fix it for results to change without refreshing it

Undefined method in controller

Posted: 28 Mar 2016 06:38 AM PDT

I'm getting an error when trying to call a method in my controller. Following tutorials on how to get this to work but just a bit stuck in the mud and need some help.

NoMethodError in CatalogController#index  undefined method `art' for #<Class:0x007fbe8c338310>  

My model

require 'httparty'  require 'json'    class Feed < ActiveRecord::Base    include HTTParty    base_uri 'https://www.parsehub.com/api/v2/runs'    # GET /feeds    # GET /feeds.json    def art      response = self.class.get("/tnZ4F47Do9a7QeDnI6_8EKea/data?&format=json")      @elements = response.parsed_response["image"]      @parsed = @elements.collect { |e| e['url'] }    end    end  

My controller

class CatalogController < ApplicationController          def index        @images = Feed.art      end      end  

I'm guessing it's something fairly simple I'm forgetting.

unx_ext 0.0.7.1 ruby 2.3.0 problems

Posted: 28 Mar 2016 06:28 AM PDT

I've got some problem with unf_ext 0.0.7.1(and more) gem. The gem is dependency to gem domain_name. The problem occured when I would like to upgrade my application form ruby 2.1.5 to 2.3.0. My system is OSX ElCaptain with zsh console. enter image description here

The same error is when I try to install this by the hand. I try also to use CC=clang, upgrade gcc to 5.3.0. Thank you for reply

Edit: My mkmf.log enter image description here

Cannot reset db with MyModel::MY_CONSTANT in routes.rb

Posted: 28 Mar 2016 06:00 AM PDT

In my routing I have the following rule

get ':index', to: 'posts#index', constraints: { index: /latest|#{Category::POSITIONS_HASH.values.join('|')}/ }  

Appearantly Postgres cannot run the migrations when I reference the model in routes before it has been created.

How do I work around this?

Ideally I'd like to have the constant defined in the model. But perhaps I'm forced to define it in a module, so that Rails don't complain?

Rails get data from child table in rails

Posted: 28 Mar 2016 06:36 AM PDT

I have three tables like

  1. users
  2. companies
  3. posts

users structure

user_id | f_name | l_name |  ---------------------------    1     |   abc  |  xyz   |  ---------------------------  #Model User  has_many :companies  

companies

company_id  |  user_id |  company_name  |  -----------------------------------------       1      |    1     |      otto      |  -----------------------------------------  #Model Company  belongs_to :user  has_many :posts, :foreign_key => :company_id  

posts

post_id  |  company_id  |  post_title  |  ----------------------------------------     1     |      1       |    helo mart |  ----------------------------------------  #Model Post  belongs_to :company  

I need view post from posts table which is created by user having user_id 1 and whose company_id is 1.

I don't know how much did it mean, because I'm newbie on ruby on rails.

Include Gem Not Working

Posted: 28 Mar 2016 05:51 AM PDT

I'm getting a weird error when I'm trying to include a gem within my controller, below is the code i'm using in the controller and the error I get is:

> undefined method `include' for <CatalogController:0x00000002427b90>  

The code returning this error is as follows:

require 'httparty'  require 'json'    class CatalogController < ApplicationController        # GET /feeds      # GET /feeds.json      def index        # GRAB THE URL        include HTTParty        base_uri 'https://www.parsehub.com/api/v2/runs'          # PARSE THE RESPONSE          def art          response = self.class.get("/tnZ4F47Do9a7QeDnI6_8EKea/data?&format=json")          @elements = response.parsed_response["image"]          @parsed = @elements.collect { |e| e['url'] }        end          end    end  

Not too sure why this error is returning?

How do I setup a reject_if on a nested, nested resource in Rails 4?

Posted: 28 Mar 2016 05:05 AM PDT

I'm getting the following error when submitting my form on my if @report.save in my report#create block.

TinyTds::Error: Cannot insert the value NULL into column 'value', table 'bane-development.dbo.measurables'; column does not allow nulls. INSERT fails.: EXEC sp_executesql N'INSERT INTO [measurables] ([measurable_type_id], [import_key], [workout_id], [created_at], [updated_at]) OUTPUT INSERTED.[id] VALUES (@0, @1, @2, @3, @4)', N'@0 int, @1 int, @2 int, @3 datetime, @4 datetime', @0 = 205, @1 = -1, @2 = 1113205, @3 = '03-24-2016 13:57:45.696', @4 = '03-24-2016 13:57:45.696'  

I've tried setting up a reject_if on my measurables model to reject saving any records that have at least one of several fields set to NULL. Though it doesn't appear to be working. The one thing that is out of the ordinary for me is I'm working on a model that is two nested levels deep in my association. I'll outline those below.

report.rb

class Report < ActiveRecord::Base    has_one :workout    accepts_nested_attributes_for :workout, allow_destroy: true  end  

workout.rb

class Workout < ActiveRecord::Base    belongs_to :report      has_many :measurables    accepts_nested_attributes_for :measurables, :allow_destroy => true,      :reject_if => proc { |attr| [:workout_id, :reliability_id, :value, :measurable_type_id].any? &:blank? }  end  

measurable.rb

class Measurable < ActiveRecord::Base    belongs_to :workout  end  

And finally here's my report_controller.rb

class Players::ReportsController < ApplicationController      def report_params        params.require(:report).permit(:author_id, :grade_id, :position_id, :type, :player_id, { alert_ids:[] }, { ncaa_game_ids:[] },        evaluations_attributes: [:explanation, :skill_id, :grade_id, :report_id, :id],        workout_attributes: [:player_id, :date, :description, :import_key, :player_workout_type_id, :all_star_game_id, :recorder_id, :field_conditions, :comments, :id, :_destroy, measurables_attributes: [:workout_id, :description, :measurable_type_id, :value, :imported_with_errors, :import_key, :order_by, :reliability_id, :id, :_destroy]])      end  end  

The thing I'm guessing might be the issue is how I have my strong parameters set up. I've not really done something this way before but, it seems that might be an incorrect way of doing things.

Rails - Register a user in stages. Starting with username

Posted: 28 Mar 2016 05:00 AM PDT

I want to change my user registration. Instead of letting the users fill in all the details at once I would like the user to fill in only the username and bring him to the registration page with the username filled in and he has to add the rest of the details.

What I have now at my landingpage (basically copy of the new user page):

  <%= form_for(@user) do |f| %>     <%= render 'shared/error_messages' %>    <%= f.label :name, "Username" %>    <%= f.text_field :name, class: 'form-control' %>      <%= f.label :email %>    <%= f.email_field :email, class: 'form-control' %>      <%= f.label :password %>    <%= f.password_field :password, class: 'form-control' %>      <%= f.label :password_confirmation, "Confirmation" %>     <%= f.password_field :password_confirmation, class: 'form-control' %>    <%= f.submit "Create my account", class: "btn btn-success btn-md  createbutton"%>       <% end %>  

My registration page is at registation_path

 <% provide(:title, 'Register') %>  <div class = "container center">  <body class ="formbody">   <center><h1>Sign up</h1></center>     <div class="row">   <div class="col-md-6 col-md-offset-3">   <%= form_for(@user) do |f| %>   <%= render 'shared/error_messages' %>          <%= f.label :name %>    <%= f.text_field :name, class: 'form-control' %>      <%= f.label :email %>    <%= f.email_field :email, class: 'form-control' %>      <%= f.label :password %>    <%= f.password_field :password, class: 'form-control' %>      <%= f.label :password_confirmation, "Confirmation" %>     <%= f.password_field :password_confirmation, class: 'form-control' %>    <%= f.submit "Create my account", class: "btn btn-success createbutton"%>     </div>  </div>  </div>  <% end %>  </body>  

I would like the user to fill in the name in 1 form at the landing page and get redirected to the registration form with the name filled in.

How to get dynamic select_tag params in controller

Posted: 28 Mar 2016 04:52 AM PDT

<%= @questions.each do |question| %>     <%= select_tag "campaign_#{question['id']}",options_from_collection_for_select(current_advertiser.campaigns.all, "id", "title", selected_value || 0) %>  <% end %>  

Now how I get the selected value in controller. Meanz they are dynamic then how I get params[?]

How to limit someone to deleting their own comment in Rails?

Posted: 28 Mar 2016 05:48 AM PDT

I am very new to Rails. I completed a tutorial here that walks you through the steps of creating a blog using it.

Part of the tutorial shows you how to create a controller that allows users to add comments to an article. I am trying to modify it so that users can only delete their own comments (and not others' comments).

Question:
Is there a way to modify the code so that way you can limit users to deleting their own comments? Any resources/tutorials are welcome too. I really just have no clue on how to start.

I feel like the right way to go is to mark the user some way when they submit the comment. Save that information in the database, and then check that information when someone goes to delete a comment. But I can't think of a way to do that without trying to build a full on log in system for users.

Code:
Here is the code from the tutorial:

Database Migration:

    class CreateComments < ActiveRecord::Migration        def change          create_table :comments do |t|            t.string :commenter            t.text :body            t.references :article, index: true, foreign_key: true              t.timestamps null: false          end        end      end  

Controller:

class CommentsController < ApplicationController    def create      @article = Article.find(params[:article_id])      @comment = @article.comments.create(comment_params)      redirect_to article_path(@article)    end      private      def comment_params        params.require(:comment).permit(:commenter, :body)      end  end  

Template:

<p>    <strong>Title:</strong>    <%= @article.title %>  </p>  <p>    <strong>Text:</strong>    <%= @article.text %>  </p>    <h2>Add a comment:</h2>  <%= form_for([@article, @article.comments.build]) do |f| %>    <p>      <%= f.label :commenter %><br>      <%= f.text_field :commenter %>    </p>    <p>      <%= f.label :body %><br>      <%= f.text_area :body %>    </p>    <p>      <%= f.submit %>    </p>  <% end %>    <%= link_to 'Edit', edit_article_path(@article) %> |  <%= link_to 'Back', articles_path %>  

Delete Comment:

class CommentsController < ApplicationController      def create        @article = Article.find(params[:article_id])        @comment = @article.comments.create(comment_params)        redirect_to article_path(@article)      end           def destroy        @article = Article.find(params[:article_id])        @comment = @article.comments.find(params[:id])        @comment.destroy        redirect_to article_path(@article)      end           private        def comment_params          params.require(:comment).permit(:commenter, :body)        end    end  

I found a similar question here, but there wasn't an answer that worked.

Rails update array by second array

Posted: 28 Mar 2016 04:40 AM PDT

I want update collection of records by array

I have products and images

product has_many :images

image belongs_to :product

and product its array of product = Product.all

and images its array of images = ['img','img1'...etc]

so i have tried update all product through image array but no luck

    product.map(&:images).each do |img|       image.each do |i|        img.update(title:i)       end     end  

How to do it?

How to use lemmatizer_base and lemmatize_ru with thinking sphinx?

Posted: 28 Mar 2016 04:35 AM PDT

How to set options: lemmatizer_base with path to dictionary and morphology: lemmatize_ru in thinking_sphinx.yml in rails application (thinking sphinx gem) ?

TimeStamps in Mongoid Embedded Documents

Posted: 28 Mar 2016 05:26 AM PDT

I am having a collection A which embeds collection B. Collection A as well as collection B includes Mongoid Timestamps (created_at and updated_at).

Now when I create a new entry of collection B (embedded object) using Rails admin, time stamps saved in Database are nil. But if I create a entry from rails console or from a normal api, then timestamps saved in database are not nil.

Any help would be appreciated.

EDIT:

class B    include Mongoid::Document    include Mongoid::Timestamps::Created    include Mongoid::Timestamps::Updated      field :user_id,    type: String    field :message,    type: String    field :status,     type: Integer, default: 1    field :spam_count, type: Integer, default: 0      embedded_in :A  

Class B is embedded in class A. When a entry of B is created inside A through rails admin, then created_at and updated_at fields of B are getting saved as nil.

getting No message given error in my Rails test

Posted: 28 Mar 2016 04:31 AM PDT

there are two models user and resident .. and both has one to one relationship (has_one) btw them. this is the test for the user(user-test.rb)

I m getting error in this test :

require 'test_helper'    class UserTest < ActiveSupport::TestCase      def setup      @resident = residents(:res1)      @user = @resident.build_user(roll_number: "101303110", email: "user@example.com",password: "foobar", password_confirmation: "foobar")    end    test "should be valid" do      assert @user.valid?    end      test "roll_number should be present" do      @user.roll_number = "     "      assert_not @user.valid?    end      test "email should be present" do      @user.email = "     "      assert_not @user.valid?    end    test "email should not be too long" do      @user.email = "a" * 244 + "@example.com"      assert_not @user.valid?    end      test "email validation should accept valid addresses" do      valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org                           first.last@foo.jp alice+bob@baz.cn]      valid_addresses.each do |valid_address|        @user.email = valid_address        assert @user.valid?, "#{valid_address.inspect} should be valid"      end    end      test "email validation should reject invalid addresses" do      invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.                             foo@bar_baz.com foo@bar+baz.com]      invalid_addresses.each do |invalid_address|        @user.email = invalid_address        assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"      end    end      test "email addresses should be unique" do      duplicate_user = @user.dup      duplicate_user.email = @user.email.upcase      @user.save      assert_not duplicate_user.valid?    end      test "password should be present (nonblank)" do      @user.password = @user.password_confirmation = " " * 6      assert_not @user.valid?    end      test "password should have a minimum length" do      @user.password = @user.password_confirmation = "a" * 5      assert_not @user.valid?    end    test "authenticated? should return false for a user with nil digest" do      assert_not @user.authenticated?(:remember, '')    end    end  

After executing the test,error came is as follows :

 1) Failure:  ResidentTest#test_should_be_valid [/Users/nischaynamdev/RubymineProjects/hostel_mess_pay/test/models/resident_test.rb:9]:  Failed assertion, no message given.    18 runs, 25 assertions, 1 failures, 0 errors, 0 skips  

user Model

the link for user model is as follows : Pls help me passing this test,I m trying since 30 minutes !

How to customize fields_for

Posted: 28 Mar 2016 04:50 AM PDT

I'm a rails newbie, today I got a problem with fields_for. Hope anyone can help me. I have a model project:

class Project < ActiveRecord::Base    validates :project_name, presence: true,uniqueness: true      validates :plan_time, presence: true    has_many :tasks, dependent: :destroy    accepts_nested_attributes_for :tasks, allow_destroy: true  end  

and a model task:

class Task < ActiveRecord::Base    belongs_to :user    belongs_to :project    validates :user_id, presence: true    validates :project_id, presence:true  end  

but when I made a form_for project:

<%= form_for(@project, do |f| %>    <%= f.fields_for :tasks do |tasks_for_form|%>    <%= render 'task_fields', f: tasks_for_form%>  <%end%>  

... it render all the existing task of the project in db. plz help me!

SIT in rails not working for audited-activerecord

Posted: 28 Mar 2016 04:34 AM PDT

I am not able to retrieve auditable_type for the child table record associated audits as it always gives parent table class name.

I have:

class Patient < ActiveRecord::Base   has_many :diseases   has_associated_audits  end    class Disease < MedicalHistory   belongs_to :patient   audited associated_with :patient  end    class MedicalHistory < ActiveRecord::Base  end  

when I make Patient.last.associated_audits.last.auditable_type give MedicalHistory instead of Disease.

Please let me know ASAP.

How to use httparty to send a post request to devise_token_auth

Posted: 28 Mar 2016 04:02 AM PDT

I am new to rails and apis. I wanted to build an api for authentication for a rails app and installed the devise_token_auth gem. I have nothing other than this gem and it is brand new app.

When I try to use HTTParty to send a post request I am getting the error

Parameters: {"{\"params\":    {\"email\":\"mail@gmail.com\",\"password\":\"abcdefgh\",\"password_confirmation\":\"abcdefgh\"}}"=>"[FILTERED]"}  Unpermitted parameter: {"params":{"email":"mail@gmail.com","password":"abcdefgh","password_confirmation":"abcdefgh"}}  Filter chain halted as :validate_sign_up_params rendered or redirected  

The documentation says

Email registration. Requires email, password, and password_confirmation params. A verification email will be sent to the email address provided. Accepted params can be customized using the devise_parameter_sanitizer system.

My httprequest:

HTTParty.post("http://localhost:3000/auth/", {:body => ["params" => {"email" => "mail@gmail.com", "password" => "abcdefgh", "password_confirmation" => "abcdefgh"}].to_json})  

What should my post look like to make this working?

Thanks, Megha

Sitemap file not found on production

Posted: 28 Mar 2016 04:08 AM PDT

I am using the sitemap_generator gem and have the following configuration at config/sitemap.rb:

require 'rubygems'  require 'sitemap_generator'    SitemapGenerator::Sitemap.default_host = 'http://www.localhost.com'    SitemapGenerator::Sitemap.create do    add '/', :changefreq => 'daily', :priority => 0.9    add '/contact', :changefreq => 'weekly'      User.find_each do |user|      add users_path(user), lastmod: user.updated_at    end  end    SitemapGenerator::Sitemap.ping_search_engines  
  • I changed my domain to localhost

The app is hosted on heroku. When I do a heroku run rake sitemap:refresh I get the following results

In '/app/public/':  + sitemap.xml.gz                                          76 links /    1.53 KB  Sitemap stats: 76 links / 1 sitemaps / 0m00s    Pinging with URL 'http://www.localhost.com/sitemap.xml.gz':    Successful ping of Google    Successful ping of Bing    Pinging with URL 'http://www.localhost.com/sitemap.xml.gz':    Successful ping of Google    Successful ping of Bing  

Now I try to find the sitemap.xml.gz file and its nowhere on heroku. I do a heroku run rake ls, heroku run rake ls tmp and heroku run rake ls public and is nowhere to be found.

In the past I had these two lines on sitemap.rb as well:

SitemapGenerator::Sitemap.public_path = 'tmp/'  SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/'  

but still the sitemaps were not generated on this folders. Any clue what I am doing wrong and is not generated?

Rails using fire-base

Posted: 28 Mar 2016 03:32 AM PDT

I have problem during using fire-base with rails to making a real time form in rails with fire-base how it will be done .. please help me i am new in fire-base. How to make a real time sharing form in Rails using fire-base.

sorry for bad English ;)

Error in OR condition in include query of Rails 4

Posted: 28 Mar 2016 04:56 AM PDT

I am using Rails 4 application where query use includes.

Query: @courses = Course.includes(:translations).unpublished_status  

Where unpublished_status is scope write in Model. (See Below):

 scope :unpublished,  -> { where(published: false) }   scope :status,  -> { where.not(status: 'active') }   scope :unpublished_status, -> { unpublished.where.or(status)}  

When i run code then got below error:

NoMethodError at /api/v1/unpublished_courses  ============================================    > undefined method `or' for #  <Globalize::ActiveRecord::QueryMethods::WhereChain:0x007fe05dbc70d8>  

Where is actual issue did not found. Any one have a idea on it.

Thanks

Rails: Skip logging backtrace

Posted: 28 Mar 2016 03:21 AM PDT

I am logging the errors of a rails application using exception_logger (https://github.com/ryancheung/exception_logger) and it is working file. But it is logging the backtrace which I don't want to be logged.

Is there any way to stop logging backtrace?

Rails image_tag full path

Posted: 28 Mar 2016 03:42 AM PDT

I have images in my assets folder and path to it

"app/assets/images/sets/img_2168.jpg"  

so i want to use it like

Dir.glob("app/assets/images/sets/*.jpg") it return me "app/assets/images/sets/img_2168.jpg"

image_tag("app/assets/images/sets/img_2168.jpg") but it gives me empty image

Is it possible if so how to fix it?

No comments:

Post a Comment