Friday, June 10, 2016

MySQL utf8mb4 in Codeship | Fixed issues

MySQL utf8mb4 in Codeship | Fixed issues


MySQL utf8mb4 in Codeship

Posted: 10 Jun 2016 07:12 AM PDT

I'm running automated tests for a Rails app in Codeship, and I'd like to use utf8mb4 as the database encoding.

Here's my modified database.yml:

test:    adapter: mysql2    host: localhost    encoding: utf8mb4    collation: utf8mb4_unicode_ci    pool: 10    username: <%= ENV['MYSQL_USER'] %>    password: <%= ENV['MYSQL_PASSWORD'] %>    database: test<%= ENV['TEST_ENV_NUMBER'] %>    socket: /var/run/mysqld/mysqld.sock  

I followed this tutorial: https://codeship.com/documentation/databases/mysql/ , but the encoding is still utf8.

How can I run the tests using a utf8mb4 encoding for the database?

Avatar has contents that are not what they are reported to be

Posted: 10 Jun 2016 07:11 AM PDT

when i try to upload an image using paper clip this is the error i face and here is the code for the paper clip insert

"has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100#>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage/.*\Z/"

Heroku - Getting a SQLite error even though it is not in the Gemfile

Posted: 10 Jun 2016 07:14 AM PDT

I've removed the sqlite3 gem from my gemfile and replaced it with pg, deleted the gemfile.lock and re-bundled, and there are no dependencies in the new gemfile.lock which require sqlite3, so why am I still getting this error?

Answered now, thanks!

Require only set of nested parameters Rails

Posted: 10 Jun 2016 07:02 AM PDT

I make a request to the server with a Json like this

{"user" : { "name" : "name", "email" : "email", "password":"pswd"}}  

So i want to only accept this format Jsons. I made this:

params.require(:user).permit(:name, :email, :password)  

But that doesnt work, i can send more parameters. I want to receive only that format or otherwise, it give an error.

Thanks!

Ruby on Rails: List of errors which each element contains the relationship

Posted: 10 Jun 2016 06:57 AM PDT

how can I generate a list of errors for the forms which each element contains the relationship (using for example an data-field attribute) with its field when it's possible? For exemple:

<form>      <div id="error_explanation">          <ul>              <li data-field="username_name">username can't be blank</li>              <li data-field="email_name">email address can't be blank</li>          <ul>      </ul>        <label for="username_field">Username</label>      <input id="username_field" name="username_name" type="text"/>        <label for="email_field">Username</label>      <input id="email_field" name="email_name" type="text"/>  </form>  

Thanks!

Calling a method of another controller

Posted: 10 Jun 2016 07:14 AM PDT

I have two controllers named Children and Father where I need to call a method of FatherController and MotherController from ChildrenController.

I need to pass a JSON data to the FatherController get_details method from set_details method of ChildrenController.

There is no route for get_details method in both controllers. I don't need any helper methods to write.

I need to call more than one Controller's method, not by Inheriting.

Father controller

class FatherController < ApplicationController      def get_details(data)      ##      ## I need to do some operation with the 'data' received from children controller.    end    end  

Mother controller

class MotherController < ApplicationController      def get_details(data)      ##      ## I need to do some operation with the 'data' received from children controller.    end    end  

Children controller

class ChildrenController < ApplicationController      data = {        "id":"2",        "expiry_date":"25-09-2016"    }.as_json      def set_details              ## get_details(data) -> FatherController      ## get_details(data) -> MotherController    end    end  

Please help how to do this or suggest me if there is any other way to do this.

Thanks.

Strong Parameters for nested omniauth

Posted: 10 Jun 2016 07:02 AM PDT

I have a Rails 4.0.13 app using Devise 3.5.10. My User model is :omniauthable using a nested authentications has_many relation, so the user can Omniauth by several providers:

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable, :confirmable,           :recoverable, :rememberable, :trackable,           :omniauthable, :omniauth_providers => Authentication.auth_methods      has_many :authentications, dependent: :destroy    accepts_nested_attributes_for :authentications  end  

(I originally implemented this some time ago on Rails 3.2, so I don't recall the exact changes I had to make to make this work. I don't believe it's relevant, but can try to look it out if necessary).

This means that a User sign-up using Omniauth has parameters like:

Parameters: {"utf8"=>"✓", "user"=>{    "authentications_attributes"=>    {"0"=>{"provider"=>"open_id",           "uid"=>"http://pretend.openid.example.com?id=12345",           "nickname"=>"http://pretend.openid.example.com"}},    "name"=>"Person1",    "email"=>"Person1@example.com", "password"=>"[FILTERED]",    "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}  

I cannot figure out how to get strong parameters to permit this. My current attempt is params.require(:user).permit(:name, :email, :password, :password_confirmation, authentications_attributes: {"0" => [:provider, :uid, :nickname]}), but that still produces a log of Unpermitted parameters: provider, uid, nickname.

How can I permit these parameters?

Configure Rails 3 for S3 bucket using fog.yml

Posted: 10 Jun 2016 06:49 AM PDT

I have this Rails 3.2 application passed on from the previous freelancer in my company. I would like to know as to how to configure this existing S3 bucket to my new EC2 Instance.
Access to AWS is configured in fog.yml by using fog gem as well as carrierwave gem.
Need urgent help. Thanks in Advance.

Can't get ng-sortable to work

Posted: 10 Jun 2016 06:48 AM PDT

I'm incorporating ng-sortable into a legacy Angular/Rails project.

My template includes this (HAML):

  %ul(as-sortable="dragQuestions" ng-model="questions")      %li(ng-repeat="question in questions")        %div(as-sortable-item-handle)          {{ question.text }}  

When I load the page I get:

Controller 'asSortableItem', required by directive 'asSortableItemHandle', can't be found!

I'm somewhat at a loss as to how to troubleshoot. Any suggestions?

Rails update instance variable on ajax call to a method from the same controller

Posted: 10 Jun 2016 07:13 AM PDT

I have a view that is handled by a simple controller:

class CountController < ApplicationController        def count          @index = 0      end  end  

In my view I just added a button:

<%= link_to "Change next day", increase_count_path(@index), :class => 'btn' :remote => true %>  

The request is being handled by a method I added in the CountController:

def increase_count      @index = params[:index].to_i + 1  end  

After trying it, I saw that each time the request is being sent to /increase_count/0 , so this obviously doesn't update the variable as I'd like it to.

So my guess is, the 2 are not linked. The first one has its scope in the view, and the second one, from the increase_count method is visible in whatever javascript I would render from it.

How can I achieve this in Rails? The thing I was trying to achieve and ran into this was the following (simplified version): I have an array of 3 Strings. Firstly I display the first one. On click I would like to make an Ajax call, increment the index, and display the next string. But I ended up showing only the second one, because the next calls don't update the index.

Can't save polygon with PostGIS via ActiveRecord

Posted: 10 Jun 2016 06:36 AM PDT

I have a problem using PostgreSQL with PostGIS via ActiveRecord. I'm using:

Rails 4.1.5  activerecord-postgis-adapter 2.2.0  PSQL 9.3.4  

When I trying to save polygon in DB, some of it saves but some are not, just returns nil for geometry column. All polygons are valid, i've check its using ST_Valid function.

polygon = <polygon> # see below    Area.find(1).update(geometry: polygon)    > UPDATE "areas" SET "geometry" = $1 WHERE "areas"."id" = 1  [["geometry", nil]]  

Direct SQL query works great, all geometry updates properly. SQL select query returns geometry or polygon.

SELECT *, ST_ASText(geometry) as geom from areas where id=1  

select results screen

ActiveRecord still returns geometry as nil.

Area.first     => #<Area id: 1, name: "Южный", geometry: nil>  

schema:

create_table "areas", force: true do |t|       t.string  "name"         t.spatial "geometry",        limit: {:srid=>4326, :type=>"geometry"}  end   

database.yml:

 development:      adapter: postgis      postgis_extension: true      schema_search_path: public,postgis      encoding: unicode      database: geo_api_development      host: localhost      pool: 5  

polygon:

POLYGON((37.613212 55.574643,37.613725 55.574608,37.635564 55.573446,37.650391 55.572547,37.650532 55.572442,37.650645 55.572335,37.650714 55.572231,37.650739 55.572125,37.650732 55.572004,37.650693 55.57189,37.650636 55.57178,37.650744 55.571755,37.650807 55.571827,37.650873 55.57189,37.651034 55.571999,37.651148 55.572059,37.651259 55.572102,37.651353 55.572116,37.651452 55.572124,37.652167 55.572132,37.652721 55.572113,37.652871 55.572122,37.653011 55.572145,37.653857 55.572301,37.667406 55.5715,37.668353 55.571476,37.669513 55.571532,37.671462 55.571666,37.67503 55.571986,37.67829 55.572483,37.68151 55.57319,37.684896 55.574226,37.685205 55.574234,37.685507 55.574221,37.686648 55.57411,37.687055 55.574063,37.687447 55.574003,37.689111 55.573653,37.689467 55.573556,37.689791 55.57343,37.690114 55.573278,37.690386 55.573125,37.691004 55.572648,37.691142 55.57246,37.69134 55.572188,37.691353 55.572144,37.691364 55.57208,37.692047 55.572213,37.691801 55.572637,37.691624 55.572943,37.691543 55.57312,37.691421 55.573494,37.691374 55.573679,37.691359 55.573838,37.691314 55.574424,37.691312 55.574645,37.691333 55.574845,37.691582 55.576139,37.691622 55.576269,37.691671 55.576394,37.691735 55.576505,37.691828 55.576627,37.691878 55.576687,37.692297 55.577091,37.698878 55.579541,37.69989 55.579917,37.701107 55.580406,37.703296 55.58122,37.714081 55.585274,37.724049 55.58915,37.726951 55.590279,37.730556 55.589765,37.73068 55.589747,37.73079 55.589725,37.730888 55.58969,37.732187 55.589088,37.733101 55.588621,37.733409 55.588827,37.73299 55.589069,37.732827 55.58918,37.732695 55.589287,37.732555 55.589406,37.732443 55.589521,37.732331 55.589662,37.732258 55.589785,37.732208 55.5899,37.732168 55.590028,37.732145 55.59016,37.732142 55.590295,37.732153 55.59042,37.732546 55.592085,37.732588 55.592209,37.732651 55.592335,37.73273 55.592449,37.732846 55.592575,37.732966 55.592687,37.733098 55.592788,37.733254 55.592897,37.733392 55.592983,37.733544 55.593059,37.733712 55.593138,37.734017 55.593272,37.735749 55.594001,37.736095 55.594188,37.736403 55.594398,37.738167 55.595123,37.738609 55.595219,37.739985 55.595776,37.740052 55.595722,37.740494 55.595899,37.740398 55.595977,37.743879 55.597367,37.751868 55.60069,37.753862 55.601595,37.756604 55.602996,37.759026 55.604564,37.781291 55.616903,37.78162 55.616985,37.781917 55.617041,37.782232 55.617072,37.782523 55.617089,37.782803 55.617091,37.784174 55.617038,37.78595 55.616943,37.786315 55.616921,37.786584 55.616891,37.786776 55.616865,37.786936 55.616829,37.787161 55.616764,37.787275 55.616714,37.787381 55.616651,37.787461 55.61659,37.787516 55.616548,37.787585 55.616522,37.787643 55.616516,37.787736 55.616517,37.787852 55.616549,37.787907 55.61659,37.787931 55.61664,37.787923 55.616692,37.787882 55.616738,37.787814 55.616773,37.787728 55.616792,37.787446 55.616816,37.787298 55.616834,37.787122 55.616861,37.786815 55.617048,37.786758 55.617083,37.786564 55.617167,37.786418 55.617219,37.786295 55.617249,37.786159 55.617272,37.78601 55.61729,37.785772 55.617308,37.784747 55.617367,37.784504 55.617392,37.784334 55.617432,37.784177 55.617481,37.784052 55.617531,37.783918 55.617607,37.783814 55.617682,37.783715 55.617762,37.783647 55.617839,37.783597 55.617923,37.783581 55.618012,37.783589 55.618099,37.783626 55.6182,37.783694 55.618302,37.78485 55.618931,37.785809 55.619461,37.786044 55.619584,37.788804 55.620814,37.790119 55.621448,37.792067 55.622491,37.793203 55.62311,37.78915 55.626421,37.785057 55.632474,37.783649 55.640978,37.785452 55.645676,37.785259 55.647043,37.783658 55.648345,37.781482 55.64879,37.777373 55.648406,37.768167 55.646009,37.749149 55.640522,37.744732 55.639772,37.733236 55.640803,37.729851 55.640768,37.71481 55.639506,37.710663 55.639791,37.69435 55.643265,37.692756 55.643782,37.675725 55.65092,37.672811 55.652779,37.671142 55.654877,37.673003 55.664958,37.675987 55.668315,37.681003 55.670599,37.702068 55.676471,37.709079 55.679581,37.712008 55.683071,37.712431 55.686925,37.710127 55.690489,37.705193 55.693449,37.684242 55.697162,37.67533 55.698177,37.670729 55.700261,37.667346 55.700467,37.667443 55.701319,37.667627 55.702943,37.667658 55.703215,37.667897 55.705326,37.663897 55.717794,37.663706 55.718391,37.663681 55.718516,37.663668 55.718666,37.663793 55.72437,37.663778 55.724526,37.663645 55.725283,37.663379 55.726405,37.663328 55.726515,37.663211 55.726757,37.662973 55.726748,37.660036 55.72669,37.659204 55.726676,37.65847 55.726085,37.658395 55.726069,37.657057 55.72585,37.656558 55.726656,37.655608 55.727896,37.65436 55.728905,37.651331 55.727571,37.651183 55.727532,37.651016 55.727511,37.65085 55.727524,37.650719 55.727572,37.650643 55.727633,37.650595 55.727705,37.650593 55.727785,37.650633 55.727864,37.650846 55.728109,37.650866 55.728175,37.650842 55.728231,37.650789 55.728278,37.64592 55.729479,37.644944 55.728191,37.644922 55.728156,37.644908 55.728119,37.644872 55.728014,37.644253 55.725478,37.644216 55.725157,37.644045 55.723698,37.644035 55.723641,37.643722 55.722447,37.641955 55.722222,37.64185 55.722223,37.641772 55.722237,37.641698 55.722257,37.641116 55.722557,37.641074 55.722575,37.641025 55.722591,37.639474 55.723045,37.639393 55.723066,37.639304 55.723083,37.63641 55.723571,37.636355 55.723293,37.635756 55.722052,37.632998 55.722626,37.632971 55.722595,37.632927 55.722574,37.630266 55.721912,37.628066 55.721428,37.628004 55.721416,37.627943 55.721407,37.627336 55.721358,37.623141 55.72102,37.622362 55.720929,37.61775 55.72032,37.615607 55.720113,37.614539 55.720957,37.614457 55.721017,37.614356 55.721064,37.614226 55.721092,37.610079 55.721457,37.609344 55.719531,37.600507 55.721271,37.59971 55.720787,37.599044 55.720333,37.598334 55.719849,37.597991 55.72001,37.597593 55.720196,37.597349 55.72003,37.596925 55.720232,37.596851 55.72018,37.594849 55.721193,37.592637 55.719598,37.592544 55.719506,37.592329 55.719086,37.590414 55.71774,37.591175 55.717403,37.59042 55.717141,37.59014 55.717098,37.589913 55.716958,37.589639 55.716691,37.589494 55.716505,37.589337 55.716122,37.589847 55.715514,37.589501 55.715244,37.589343 55.715146,37.58788 55.714069,37.588491 55.713807,37.587891 55.713365,37.588449 55.713124,37.585667 55.711068,37.585113 55.711308,37.584562 55.710902,37.583218 55.710865,37.582803 55.711191,37.582049 55.710883,37.583247 55.709979,37.586231 55.708101,37.587404 55.70639,37.587569 55.706148,37.588074 55.705607,37.594741 55.697437,37.595336 55.696797,37.596028 55.696134,37.596788 55.695458,37.600568 55.692399,37.601193 55.691929,37.601669 55.69163,37.602083 55.69137,37.602958 55.690907,37.603905 55.690499,37.604989 55.690134,37.605537 55.689973,37.60389 55.688198,37.600143 55.684136,37.604546 55.684231,37.604872 55.684234,37.60512 55.684231,37.605384 55.684218,37.605706 55.684186,37.60808 55.683907,37.608393 55.683878,37.60869 55.683865,37.609016 55.683858,37.609398 55.68386,37.609842 55.683879,37.613557 55.68434,37.613575 55.684472,37.613571 55.684599,37.61369 55.684621,37.613819 55.684646,37.615206 55.684886,37.615818 55.684951,37.616548 55.684981,37.617241 55.684934,37.617837 55.684838,37.618385 55.684696,37.618763 55.684488,37.618832 55.684265,37.618411 55.683831,37.618334 55.68378,37.618242 55.68372,37.6173 55.683357,37.61712 55.683257,37.616937 55.683089,37.616047 55.68214,37.615879 55.682022,37.615607 55.681912,37.61481 55.681715,37.614664 55.681632,37.614606 55.681482,37.614782 55.680976,37.614738 55.680779,37.614569 55.680597,37.611686 55.678521,37.611579 55.678384,37.611535 55.678235,37.611519 55.677425,37.611414 55.677304,37.611294 55.677221,37.611146 55.677168,37.610785 55.677117,37.610592 55.677083,37.610375 55.677008,37.60933 55.676463,37.609187 55.676389,37.609098 55.676292,37.608924 55.675608,37.608879 55.675482,37.608768 55.67537,37.607581 55.67467,37.607457 55.674582,37.607403 55.67449,37.607248 55.674135,37.607151 55.674026,37.606953 55.673876,37.606156 55.673464,37.605221 55.673185,37.60531 55.672777,37.605935 55.672358,37.60587 55.672275,37.605861 55.672233,37.605865 55.67218,37.605971 55.671916,37.606003 55.671885,37.606608 55.671472,37.606631 55.671426,37.606625 55.671357,37.606646 55.671299,37.606934 55.671107,37.606969 55.671084,37.60702 55.671045,37.607046 55.670996,37.607037 55.669639,37.607021 55.66866,37.607042 55.668612,37.607077 55.668565,37.607113 55.668533,37.607152 55.668504,37.6116 55.66614,37.611782 55.666035,37.611261 55.665695,37.611187 55.665612,37.611154 55.665512,37.610847 55.665469,37.609279 55.665371,37.609179 55.665349,37.609011 55.665413,37.608962 55.665376,37.607636 55.664305,37.607564 55.664247,37.607523 55.664097,37.611105 55.663733,37.611764 55.663637,37.613353 55.663476,37.605882 55.657358,37.605655 55.657172,37.605465 55.65698,37.605288 55.656736,37.605239 55.656668,37.605204 55.656602,37.605179 55.656525,37.605165 55.656442,37.605432 55.642373,37.6054 55.641347,37.594217 55.641991,37.593206 55.642068,37.592137 55.642164,37.591328 55.642246,37.590602 55.64234,37.589911 55.642457,37.589176 55.642622,37.58853 55.642789,37.586692 55.643298,37.579797 55.645429,37.579758 55.645389,37.579846 55.644712,37.579789 55.643996,37.579768 55.643935,37.579687 55.64377,37.579643 55.643725,37.579584 55.643685,37.579095 55.643377,37.57904 55.643314,37.578997 55.643232,37.578989 55.64316,37.579053 55.642831,37.579091 55.642778,37.57916 55.642739,37.579242 55.642712,37.579916 55.642631,37.580709 55.642357,37.580784 55.642321,37.580834 55.642274,37.581159 55.64175,37.581213 55.641683,37.581291 55.641634,37.581891 55.641263,37.581915 55.641216,37.581914 55.641166,37.58188 55.64112,37.581819 55.641101,37.581146 55.640997,37.581094 55.640968,37.581068 55.640923,37.581079 55.640877,37.581335 55.640447,37.581336 55.640447,37.581463 55.639449,37.581443 55.639003,37.58157 55.638933,37.582327 55.638517,37.581715 55.637165,37.581715 55.637165,37.581154 55.637286,37.580619 55.636476,37.580192 55.636338,37.578133 55.634622,37.578 55.634503,37.577997 55.63448,37.57801 55.634459,37.578034 55.634443,37.578075 55.634431,37.578189 55.634414,37.584646 55.633792,37.585885 55.633634,37.587923 55.63339,37.587924 55.633381,37.587947 55.633272,37.587947 55.633271,37.587952 55.633261,37.587961 55.633251,37.587978 55.633242,37.588027 55.633221,37.587853 55.633143,37.587397 55.632926,37.587241 55.632831,37.587128 55.632729,37.587026 55.632618,37.58696 55.632518,37.5866 55.631582,37.587826 55.631588,37.588469 55.631753,37.590045 55.631844,37.590172 55.631851,37.590286 55.631839,37.590387 55.631814,37.590979 55.631665,37.591052 55.631633,37.591121 55.631587,37.591159 55.631535,37.591332 55.631094,37.591341 55.631047,37.591339 55.631001,37.59133 55.630952,37.59033 55.629273,37.589697 55.629403,37.589298 55.628782,37.588655 55.628914,37.588219 55.628236,37.590297 55.627825,37.590254 55.627692,37.590226 55.627427,37.590239 55.627187,37.590274 55.627052,37.590223 55.627033,37.589152 55.62694,37.589074 55.626923,37.589004 55.626894,37.588971 55.626847,37.588688 55.626238,37.587 55.626588,37.586661 55.625877,37.58696 55.625831,37.586559 55.625208,37.586343 55.624202,37.586307 55.624043,37.586259 55.623979,37.586173 55.623923,37.586031 55.623902,37.585892 55.623903,37.585765 55.62393,37.585658 55.623964,37.585606 55.624026,37.585599 55.624088,37.585859 55.625119,37.583849 55.625342,37.583608 55.624672,37.583589 55.624619,37.583293 55.623794,37.583236 55.623635,37.584344 55.623463,37.584403 55.623297,37.584579 55.623169,37.583897 55.622273,37.58262 55.621268,37.581148 55.621053,37.578773 55.62192,37.577984 55.622091,37.577028 55.622148,37.576903 55.622136,37.576787 55.62211,37.576716 55.622066,37.575859 55.621234,37.575002 55.619971,37.577297 55.619206,37.578799 55.619011,37.579946 55.618536,37.581004 55.618364,37.579866 55.617096,37.579835 55.617037,37.579834 55.616987,37.579876 55.616937,37.579953 55.616905,37.58021 55.616862,37.580801 55.616794,37.580849 55.616769,37.580888 55.616738,37.580923 55.616699,37.580939 55.616656,37.580698 55.616117,37.580631 55.616029,37.580545 55.615955,37.57764 55.614663,37.574681 55.613358,37.574952 55.613161,37.575793 55.612457,37.575522 55.61024,37.575015 55.609767,37.574709 55.607907,37.574716 55.607783,37.574744 55.607674,37.575146 55.606904,37.575246 55.606785,37.575327 55.606689,37.577031 55.605052,37.577481 55.604562,37.577532 55.604526,37.577661 55.604494,37.579504 55.604472,37.581448 55.604447,37.58157 55.604429,37.581664 55.604372,37.581695 55.604304,37.581553 55.603518,37.58153 55.603412,37.581483 55.603318,37.580027 55.601684,37.579984 55.601594,37.579955 55.601486,37.580165 55.598047,37.580204 55.597982,37.580279 55.597929,37.580349 55.597898,37.579958 55.596031,37.579074 55.596085,37.578557 55.595291,37.578931 55.595213,37.578068 55.593651,37.578032 55.593576,37.578012 55.593505,37.577898 55.592818,37.577896 55.592746,37.577955 55.592664,37.577344 55.589332,37.576978 55.58773,37.576952 55.587612,37.576972 55.587495,37.577015 55.587374,37.577132 55.587259,37.577369 55.587153,37.577375 55.587149,37.57738 55.587147,37.577514 55.587056,37.577604 55.586942,37.577621 55.586831,37.575486 55.583851,37.573599 55.581842,37.573544 55.581723,37.573427 55.581569,37.572668 55.580991,37.588241 55.577256,37.589243 55.577022,37.589869 55.576921,37.591017 55.576527,37.591291 55.576404,37.591519 55.576279,37.59179 55.576099,37.592022 55.575924,37.59223 55.575712,37.592358 55.575575,37.593931 55.573548,37.595221 55.572283,37.595751 55.571841,37.596276 55.57141,37.598559 55.56975,37.599432 55.569045,37.599774 55.568549,37.599999 55.568265,37.600267 55.5685,37.601918 55.56648,37.601991 55.566497,37.601572 55.567233,37.601443 55.56751,37.601317 55.567816,37.601224 55.568111,37.600874 55.569347,37.600772 55.569636,37.600663 55.570025,37.600531 55.570436,37.600356 55.570634,37.599988 55.571039,37.599833 55.571182,37.599769 55.571249,37.599653 55.571436,37.599613 55.571535,37.598815 55.571991,37.598709 55.572074,37.598574 55.572206,37.598438 55.572366,37.598182 55.572668,37.598063 55.572868,37.597936 55.573161,37.597918 55.573353,37.597827 55.573671,37.597815 55.573738,37.597816 55.573792,37.597825 55.573858,37.597867 55.573925,37.597918 55.573996,37.597972 55.574046,37.598544 55.574449,37.599887 55.575266,37.600011 55.575327,37.600167 55.575386,37.600313 55.575439,37.600709 55.575559,37.600807 55.575581,37.601016 55.575595,37.602511 55.57551,37.602971 55.575483,37.603164 55.575432,37.60342 55.575348,37.603652 55.575247,37.60383 55.575129,37.604109 55.574829,37.604087 55.574683,37.604066 55.574507,37.603992 55.57436,37.603991 55.574335,37.604006 55.57432,37.604033 55.574312,37.60406 55.574308,37.604096 55.574317,37.604544 55.574574,37.605512 55.575114,37.613212 55.574643))  

How can I get it to work?

adding each_slice(3) gives Error in rails App

Posted: 10 Jun 2016 06:45 AM PDT

I´m working on this do loop in my app, it works fine but I want to take it further(see below) and I´m not sure how to do that. ( I´m a rails newbie)

<div class="row">        <% @products.each do |category, products| %>          <% products.each_with_index do |product, index| %>          <% if index == 0 %>              <div class="col-lg-4 col-sm-6 col-xs-12 center-block " >                        <%= image_tag product.image.url(:medium), class: "img-responsive" %>              <div class="caption">                  <p><%= product.category.name %></p>               </div>               <% end %>              </div>           <% end %>      <% end %>    </div>  

At the moment the loop is looping through 12 categories and displaying one image from each category. I don´t want to have all the images appearing in the same row.

I tried to add each_slice(3) to the loop but it gives me this error undefined method 'image' for 5:Fixnum

this is how the code looks after the each_slice(3) insertion

    <% @products.each_slice(3) do |category, products| %>          <div class="row">              <% products.each_with_index do |product, index| %>                  <% if index == 0 %>                      <div class="col-lg-4 col-sm-6 col-xs-12 center-block " >                        <%= image_tag product.image.url(:medium), class: "img-responsive" %>              <div class="caption">                  <p><%= product.category.name %></p>               </div>               <% end %>              </div>           <% end %>      <% end %>    </div>  

I´m not sure what to do here or if each_slice(3) is the right way to do this.

I hope someone here can guide me through this

thanks D

create admin for spree for the app on heroku

Posted: 10 Jun 2016 06:26 AM PDT

How can I create an admin for my app which is running on heroku with spree.

Here's what I am trying but doesn't seem to be working.

new_admin=Spree::User.create(:email=>"test@gmail.com",  :password =>"testtest", :password_confirmation =>"testtest")  

I am going into heroku rails console, and trying it.

Please help.

Live branding semantic-ui on rails

Posted: 10 Jun 2016 06:24 AM PDT

I'm using rails 4 with the less-rails-semantic-ui gem and I need to allow for custom branding on a per-user basis.

I like how semantic has variables that can be set on the top level and propagated through the rest of the css, but an initial render after changing a variable can take up to 15 seconds to load the page.

Is there a way to take advantage of semantic-ui's variables and implement per-user branding, while keeping decent page load times? Can I precompile all of the assets that don't include specific variables, and then compile those on render?

One possibility is to duplicate the code from the gem and render a css.erb file that is loaded on each request. But that feels messy.

Ruby on rails submit button doesn't call the controller

Posted: 10 Jun 2016 06:19 AM PDT

I am new to ruby on rails, I want to make a simple Text Field where you can change the content and store it in the database. But the submit button doesn't call the Profiles controller. "Foo" is never raised.

routes.rb:

Rails.application.routes.draw do     devise_for :users     get 'welcome/user'     resources :profiles  end  

user.html.erb:

...  <%@profile=Profile.find_by user_id: current_user.id%>  <%= form_for (@profile) do |f| %>  <%= f.text_field :name%>  <%= f.submit%>  <% end %>  

profiles_controller.rb:

class ProfilesController < ActionController::Base    def update       raise "foo"    end  end  

ruby on rails website on two language

Posted: 10 Jun 2016 05:57 AM PDT

how to make a website in two languages on rails? use gem or create two projects or register two domains? help me, please. Link or quick explanation of the ideas as it is accepted to do

Where not null for reference column showing error - rails

Posted: 10 Jun 2016 06:16 AM PDT

I want to query a table where multiple referenced column in not null.

I tried like this: JobTypePresetting.where('comment_text == ?', nil) JobTypePresetting.where('comment_text_id == ? OR part_listing_id == ?', nil, nil)

Even first is not working showing error like

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer == unknown  LINE 1: ...resettings"."template_id" = $2 AND (comment_text_id == NULL)                                                             ^  HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.  

How do i query this, currently i'm using like

JobTypePresetting.where('comment_text_id is not null or part_listing_id is not null')  

Rails: How to sum and display total quantity by category

Posted: 10 Jun 2016 07:05 AM PDT

I'd like to sum total quantities by category.

How can I calculate and display them?

The display image is as followings; (item A and C are the same category)

order A    shop A        name: item A      category: 1      quantity: 2        name: item B      category: 2      quantity: 3        name: item C      category: 1      quantity: 4        <Total>     # I'd like to know how to calculate and display      category 1: 6      category 2: 3  

So it would be appreciated if you could give me any advice.

models

class Order < ActiveRecord::Base      has_many :shops  end    class Shop < ActiveRecord::Base      belongs_to :order      has_many :items  end    class Item < ActiveRecord::Base      belongs_to :shop      has_one :order, autosave: false, through: :shop  end  

schema.rb

ActiveRecord::Schema.define(version: 20160610051929) do      create_table "items", force: :cascade do |t|      t.string   "name"      t.integer  "category"      t.integer  "quantity"      t.integer  "shop_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "orders", force: :cascade do |t|      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "shops", force: :cascade do |t|      t.string   "name"      t.integer  "order_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end  

orders_controller.rb

class OrdersController < ApplicationController    def show      @orders = Order.find(params[:id])    end  end  

view/orders/show.html.erb

<%= render @orders %>  

view/orders/ _order.html.erb

<%= order.name %><br>    <% order.shops.each do |shop| %>        <%= shop.name %><br>        <% shop.items.each do |item| %>            name: <%= item.name %><br>          category: <%= item.category %><br>          quantity: <%= item.quantity %><br>          <br>        <% end %>    <% end %>  

It would be appreciated if you could give me how to calculate and display in total.

Rails Custom Validation/Callback from External API

Posted: 10 Jun 2016 05:34 AM PDT

Using Easy Post API, I want to validate customer addresses, update my DB with the easy post response, and also provide useful feedback to my users...but what is correct? #3 below is what I really need help with!

  1. Should I use EP response to update user-input (meaning a user will see their zip/city/street updated to something different than they entered), or just tie that record to the easy_post id, so I can retrieve that info from EP, but users will still see their own address as they entered it (provided it's valid)?
  2. How do I provide individual field verifications?

Granted, this is sloppy, but I need feedback/help.

  1. Should I initialize EasyPost every time this callback is performed?

  2. If I should update the db from EP's response, is this the right way?

  3. EP response error hash will have a key for each field that's no good. How can I use that to mark those fields invalid in the rails way?


validate :easy_post_valid    def easy_post_valid    addr = self    begin      EasyPost.api_key = ENV['EP_SECRET_KEY']      address_check = EasyPost::Address.create(        verify: ["delivery"],        street1: addr.street1, # street1 will fail validation        city: addr.city,        state: addr.state,        zip: addr.zip,        country: "US"      )      if !address_check.verifications.delivery.success        address_check.verifications.delivery.errors.each do |e|          errors.add :base, e.message        end        puts address_check.verifications        return false      elsif address_check.verifications.delivery.success        self.ep_id  = address_check.id        self.street1 = address_check.street1        self.street2 = address_check.street2        self.city = address_check.city        self.state = address_check.state        self.zip = address_check.zip        self.city = address_check.city      end    end    true  end  

Devise current_user undefined after sign up but not login

Posted: 10 Jun 2016 05:26 AM PDT

I have a user model with an admin submodel.

class Admin < User  end  

I have devise set up and a 'type' column in the user model. The routes look like this:

devise_for :users, :controllers => { :sessions => 'sessions' }, :skip => :registrations  devise_for :admins, :skip => :sessions  

When I sign up as an admin the current_admin helper works but current_user is undefined.

Then, when I sign out and sign in as a user current_user works.

How can I set an admin to be a user right at registration?

Devise, where to add a model

Posted: 10 Jun 2016 05:49 AM PDT

I want to add a timeoutable model to devise after my initial configuration.

I enabled the config/initializers/devise.rb:

config.timeout_in = 30.minute  

But where do I actually add the devise :timeoutable model?

Rails 4: Moving Active Record generated collections from view to model

Posted: 10 Jun 2016 05:24 AM PDT

Starting with Rails and I would like to move ORM part from view to model.

How to do it?

Example:

 <%= f.collection_check_boxes :instructor_ids, Instructor.joins(:events).where(events: { :start_time => Date.today.beginning_of_week..Date.today.end_of_week }).group("instructor_id").having("count(instructor_id) < 4"), :id, :name do |ib| %>    <%= ib.label(class: "checkbox-inline input_checkbox") {ib.check_box(class: "checkbox") + ib.text } %>   <% end %>  

Thanks.

Lloop showing unwanted div´s when going through categories

Posted: 10 Jun 2016 05:40 AM PDT

I´m working with this loop in my views/pages/index.html.erb

<div class="container-fluid">    <div class="row">      <% @products.each do |category, products| %>        <% products.each_with_index do |product, index| %>          <div class="col-lg-4 col-sm-6 col-xs-12 center-block">            <% if index == 0 %>              <%= image_tag product.image.url(:medium), class: "img-responsive" %>              <div class="caption">                <p><%= product.category.name %></p>              </div>             <% end %>          </div>         <% end %>      <% end %>    </div>  </div>  

it works fine and does what it is supposed to do which is to loop through each category and present the last picture added to each category.

But the problem is when I´m adding products and assigning them to categories in views/products/new.html.erb the loop above seems to add extra empty div'sto the row. I don´t understand why it is doing that... can anyone give me a hint why this is happening?

this is a screenshot how it appears in google dev tools screenshot

As you can see there are four empty unwanted divs in the row.

Rails select tag add numbers at interval

Posted: 10 Jun 2016 04:47 AM PDT

I have select tag <%= f.select :yxxx, options_for_select([['10','10'],['20','20'],['30','30'],['40','40']], :selected => model.yxxx), {}, { :class => 'yxxx form-control', style: "width:125%;" } %>

i want to add ruby code to dynamically populate option for select. this function gives me the required options (1..4).each { |n| puts n * 10 } How can i add this to the select tag

Form not this saving some data

Posted: 10 Jun 2016 06:40 AM PDT

I have a form, there are some data not saved, do not understand why:

This data is automatically filled with a javascript of a webservice. Just by entering the cep.

The data are not saved:

Cep:

Rua:

Bairro:

Cidade:

Estado:

My form:

    <%= simple_form_for(@profissional)  do |f| %>    <%= f.error_notification %>      <div class="col-md-offset-3 col-md-6 singup-couple">        <div class="well-box">          <h2>Informe sua categoria</h2>          <div class="form-group">            <%= f.collection_select :categoria, Segmento.order(:categoria), :id, :categoria, prompt: 'Selecione uma Categoria', input_html: { class:'form-control'} %>            <br>            <%= f.grouped_collection_select :subcategoria, Segmento.order(:categoria), :subcategorium, :categoria, :id, :classe, prompt: 'Selecione uma Categoria', input_html: { class:'form-control' } %>            <%= f.input :sugerir, label: 'Sugira uma nova Categoria', input_html: { placeholder:'Sugira uma nova Categoria' }  %>            <%= f.input :profissionalnome, label: 'Nome do Profissional ou Empresa', input_html: { placeholder:'Informe Seu Nome Completo ou o Nome de Sua Empresa' } %>            <%= f.input :email, label: 'E-mail', input_html: { placeholder:'Digite Seu E-mail' } %>            <%= f.input :cep, label: 'CEP', input_html: { name: 'cep', type:'text', id: 'cep', value: '', size: '10', maxlength:'9', onblur: 'pesquisacep(this.value);', placeholder:'Digite seu CEP', label: 'CEP', label_method: 'Buscar CEP'} %>            <%= f.input :rua, label: 'Endereço Completo', input_html: { name: 'rua', type:'text', id: 'rua', value: '', size: '60', placeholder:'Informe seu Endereço'} %>            <%= f.input :bairro, input_html: { name: 'bairro', type:'text', id: 'bairro', value: '', size: '40', placeholder:'Informe seu Bairro'} %>            <%= f.input :cidade, input_html: { name: 'cidade', type:'text', id: 'cidade', value: '', size: '40', placeholder:'Informe sua Cidade'} %>            <%= f.input :estado, input_html: { name: 'uf', type:'text', id: 'uf', value: '', size: '2', placeholder:'Informe Seu Estado'} %>            <%= f.input :telefone, label: 'Telefone', input_html: { placeholder:'Informe Seu Telefone' } %>            <%= f.input :celular, label: 'Celular', input_html: { placeholder:'Informe Seu Celular' } %>            <%= f.collection_select :operadora, Operadora.order(:operadoras), :id, :operadoras, prompt: 'Selecione uma Operadora' %><br>              <%= f.check_box :termos %>          </div>          <div class="form-actions">            <%= f.button :submit, value: 'Criar Perfil Profissional' %>          </div>        </div>      </div>  <% end %>  

My javascript:

  <script type="text/javascript" >      function limpa_formulário_cep() {      //Limpa valores do formulário de cep.      document.getElementById('rua').value=("");      document.getElementById('bairro').value=("");      document.getElementById('cidade').value=("");      document.getElementById('uf').value=("");      //document.getElementById('ibge').value=("");    }      function meu_callback(conteudo) {      if (!("erro" in conteudo)) {        //Atualiza os campos com os valores.        document.getElementById('rua').value=(conteudo.logradouro);        document.getElementById('bairro').value=(conteudo.bairro);        document.getElementById('cidade').value=(conteudo.localidade);        document.getElementById('uf').value=(conteudo.uf);        //document.getElementById('ibge').value=(conteudo.ibge);      } //end if.      else {        //CEP não Encontrado.        limpa_formulário_cep();        alert("CEP não encontrado.");      }    }      function pesquisacep(valor) {        //Nova variável "cep" somente com dígitos.      var cep = valor.replace(/\D/g, '');        //Verifica se campo cep possui valor informado.      if (cep != "") {          //Expressão regular para validar o CEP.        var validacep = /^[0-9]{8}$/;          //Valida o formato do CEP.        if(validacep.test(cep)) {            //Preenche os campos com "..." enquanto consulta webservice.          document.getElementById('rua').value="...";          document.getElementById('bairro').value="...";          document.getElementById('cidade').value="...";          document.getElementById('uf').value="...";          //document.getElementById('ibge').value="...";            //Cria um elemento javascript.          var script = document.createElement('script');            //Sincroniza com o callback.          script.src = '//viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';            //Insere script no documento e carrega o conteúdo.          document.body.appendChild(script);          } //end if.        else {          //cep é inválido.          limpa_formulário_cep();          alert("Formato de CEP inválido.");        }      } //end if.      else {        //cep sem valor, limpa formulário.        limpa_formulário_cep();      }    };    </script>  

My Controller

    class ProfissionalsController < ApplicationController    before_action :authenticate_user!, :except => [:show, :index]    before_action :set_profissional, only: [:show, :edit, :update, :destroy]        # GET /profissionals    # GET /profissionals.json    def index      @segmentos = Segmento.all      @operadoras = Operadora.all      @profissionals = Profissional.all    end      # GET /profissionals/1    # GET /profissionals/1.json    def show    end      # GET /profissionals/new    def new      @segmentos = Segmento.all      @operadoras = Operadora.all      @profissional = Profissional.new    end      # GET /profissionals/1/edit    def edit    end      # POST /profissionals    # POST /profissionals.json    def create      @profissional = Profissional.new(profissional_params)        respond_to do |format|        if @profissional.save          format.html { redirect_to @profissional, notice: 'Profissional was successfully created.' }          format.json { render :show, status: :created, location: @profissional }        else          format.html { render :new }          format.json { render json: @profissional.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /profissionals/1    # PATCH/PUT /profissionals/1.json    def update      respond_to do |format|        if @profissional.update(profissional_params)          format.html { redirect_to @profissional, notice: 'Profissional was successfully updated.' }          format.json { render :show, status: :ok, location: @profissional }        else          format.html { render :edit }          format.json { render json: @profissional.errors, status: :unprocessable_entity }        end      end    end      # DELETE /profissionals/1    # DELETE /profissionals/1.json    def destroy      @profissional.destroy      respond_to do |format|        format.html { redirect_to profissionals_url, notice: 'Profissional was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_profissional        @profissional = Profissional.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def profissional_params        params.require(:profissional).permit(:categoria, :subcategoria, :sugerir, :profissionalnome, :email, :cep, :rua, :bairro, :cidade, :estado, :ibge, :telefone, :celular, :operadora, :termos, :user_id)      end  end  

someone help me?

thanks.

How to handle "puts 'Found!' if User.where(id: 0)" in Rails?

Posted: 10 Jun 2016 05:26 AM PDT

Take a look at these codes.

pry> puts User.find_by(id: 0) ? 'Found!' : 'Not found'  Not found    pry> puts User.where(id: 0) ? 'Found!' : 'Not found'  Found!  

The first one is ok but the second one User.where(id: 0) returns an empty Array which is evaluated as true in an if condition clause in Ruby.

I know there are some ways to avoid this problem. One of them is using empty? or present? method when you try to fetch "multiple rows" like:

users = User.where(country: 'vietnam')    if users.empty?    ...  

I think it's ok to use empty? or present?. But when you try to fetch a single row, you don't have to use such methods because when there is no row, it returns nil.

What I'm worried about is that sometimes you need empty? and sometimes you don't need empty?. Then the codes becomes hard to read.

So I thought it might be good that I always use empty? whether a method returns multiple rows or a single row. But now I don't want to see empty? methods all over my codes.

Is there any good way to handle this?

Can you copy/move an uploaded file from one model to another model

Posted: 10 Jun 2016 04:36 AM PDT

Is it possible to copy/move a file from one model to another model. I have two models TemporaryAttachment and DocAttachment. TemporaryAttachment is to temporary store the files the user uploads while they are processing a form. Once they are finished and they want to submit their data it should move/copy the TemporaryAttachments temp_attachment attribute to DocAttachments attachment attribute.

Below is the TemporaryAttachment model

class TemporaryAttachment < ActiveRecord::Base    has_attached_file :temp_attachment,                  storage: :filesystem,                  path: 'public/assets/dev/images/docs/:id_partition/:filename',                  url: Rails.application.config.x.local_url        validates_attachment_presence :temp_attachment      do_not_validate_attachment_file_type :temp_attachment        validates_attachment_size :temp_attachment, less_than: 10.megabytes  end  

Below is the DocAttachment model

class DocAttachment < ActiveRecord::Base    belongs_to :doc_attachment_type    belongs_to :language    belongs_to :upload    belongs_to :creator, foreign_key: 'creator_id', class_name: 'User'      has_attached_file :attachment      before_save :rename_file      validates_attachment_presence :attachment      validates_attachment_content_type :attachment,                                      content_type: %w(application/pdf application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document text/plain),                                      size: { :in => 0..10.megabytes }      validates :doc_attachment_type_id, presence: true    validates :code, presence: true    validates :title, presence: true    validates :language_id, presence: true      def rename_file      extension = File.extname(attachment_file_name).gsub(/^\.+/, '')      filename = attachment_file_name.gsub(/\.#{extension}$/, '')      new_attachment_file_name = "#{self.code}-#{self.language.name}.#{extension}"        attachment.instance_write(:file_name, new_attachment_file_name)      end    end  

This is the TemporaryAttachments controller which is called to upload one or more files

class TemporaryAttachmentsController < ApplicationController      def create        temp_doc_attachment_params[:temp_attachment_array].each do |file|          @temp_attachment = TemporaryAttachment.new        @temp_attachment.temp_attachment = file        @temp_attachment.save      end        redirect_to new_upload_path    end      private      def temp_doc_attachment_params      params.require(:temporary_attachment).permit(temp_attachment_array: [])    end    end  

This is the uploads controller which is used to copy temp attachments over to doc attachments and sets a couple other attributes.

class UploadsController < ApplicationController    def new      @upload = Upload.new      @temp_attachments = TemporaryAttachment.all      @languages = Language.order(:name)      copy_temp_attachments      @doc_attachments = @upload.doc_attachments    end      def create      @upload = Upload.new(upload_params)        if @upload.save        TemporaryAttachment.destroy_all        render doc_attachments_confirmation_path      else        render action: 'new'      end    end      def delete    end      private      def upload_params      params.require(:upload)          .permit(doc_attachments_attributes: [                      :id,                      :code,                      :title,                      :language_id,                      :doc_attachment_type_id                  ])    end      def params_with_user      form_params =  doc_attachment_params      form_params[:creator_id] = @user.id      form_params    end      def copy_temp_attachments      if @temp_attachments.present?        @temp_attachments.each do |temp_file|          get_file_details temp_file.temp_attachment_file_name          @upload.doc_attachments.build({attachment: temp_file.temp_attachment,                                         code: @details.first,                                         language_id: @details.last})        end      end    end      def get_file_details(filename)        @details = filename.split('-')        extension = File.extname(@details.last).gsub(/^\.+/, '')      filename = @details.last.gsub(/\.#{extension}$/, '')        filename = 'wel' if filename.eql? "cym"      language = Language.where('languages.name LIKE :lang', {:lang => "%#{filename.capitalize}%"})        @details[2] = language.first.id      end  end  

When I try this I an error stating that doc_attachments.attachment can't be blank. I'm assuming thats being the model is looking for a file and its not available.

Any help greatly appreciated.

Why does Mongoid's "presence" validation enable autosave?

Posted: 10 Jun 2016 05:10 AM PDT

I had a hard time debugging this one and I was about to ask for help. But I've managed to identify the cause and would like to share my findings in case someone else is running into the same problem. [And maybe someone can explain why it works the way it does]

Setup

Let's say I have two Mongoid-Documents, Customer and Order with a 1:n relation. In addition, Customer has an after_save callback to synchronize document changes with an external API:

class Customer    include Mongoid::Document    has_many :orders    after_save do      puts "synchronizing customer" # <- not my actual code    end  end    class Order    include Mongoid::Document    belongs_to :customer    validates_presence_of :customer  end  

Everything works as expected. Creating and updating customers results in the after_save callback being triggered and creating orders does not.

Change

After a while, Customer needs a new field with a default value:

class Customer    # ...    field :premium, type: Boolean, default: false  end  

Problem

But all of a sudden, things get weird. After this change, creating (or updating) orders result in the customer being saved as well! (I noticed this because of my logs – the synchronization was running for no apparent reason)

c = Customer.last  c.orders.create  synchronizing customer  # <- what the?  #=> #<Order _id: 575a995aab265d730b8bddba ...>  

Strangely, this only happens for existing customers and it only occurs once.

Cause

A long and tedious debugging session revealed that the Order's belongs_to relation has an autosave flag:

Order.relations['customer'].autosave?  #=> true  

It was enabled by the presence validation and in fact, Mongoid's documentation notes it casually:

Note that autosave functionality will automatically be added to a relation when using accepts_nested_attributes_for or validating presence of the relation.

But autosave only saves a document if it was changed, so where did the change come from? Apparently, my new premium field with the default value introduced a subtle change:

c = Customer.first # a customer from before the change without "premium" attribute  c.changed?  #=> true  c.changes  #=> {"premium"=>[nil, false]}  

Solution

After all, the fix was quite trivial. I just had to explicitly disable autosave on my belongs_to relation:

class Order    include Mongoid::Document    belongs_to :customer, autosave: false    validates_presence_of :customer  end  

Open Questions

But the question remains: Why does Mongoid's "presence" validation enable autosave? How could this be the desired default behavior? Please enlighten me.

Disable s3_uploader_form once image is uploading or uploaded to s3

Posted: 10 Jun 2016 06:21 AM PDT

I am uploading images on s3 through s3_direct_upload gem. I want to upload one image at a time. When one image uploaded on s3 uploader, the button should be disabled. I have tried in javascript to disable it but wasn't able to do so. Following is the code to upload :

<div class="col-lg-12">                        <%= s3_uploader_form :key=> "Ad/Images/{unique_id}/${filename}",:key_starts_with=> "Ad/",id: "s3-uploader_image"  , max_file_size: 2.megabytes do %>      <%= hidden_field_tag 'Content-type', '' %>      <%= file_field_tag :file,:multiple=>false,:class=>"thumbnail_image",accept: 'image/png,image/gif,image/jpeg'  %>      <% end %>   </div>  

Can anyone help to disable this s3_uploader_form once image uploaded successfully on s3.

Skip before action not skipping in Rails 4

Posted: 10 Jun 2016 05:17 AM PDT

I have used skip before action so that the application should allow the four pages(client_details,client_process,login,validate_login). But the action does not works as I expected. It is not allowing the user to login. I dont know why. Kindly please help.

My Users controller,

class UsersController < ApplicationController    skip_before_action :check_session, :only=>[:client_details,:client_process,:login,:validate_login]    require 'securerandom'    def client_details      @client=Client.new    end      def client_process      params.permit!      @client=Client.new(client_params)      if @client.save        Notify.scop(@client).deliver        flash[:notice] = " your infomation is registered,wait for approval"        redirect_to :action=> "login"      else         render "client_details"         flash[:notice] = "sorry..."      end    end      def login      @user=User.new      render :layout=>false   end     def validate_login     params.permit!     @user=User.where params[:user]     $userid=@user.pluck(:id)[0]     if not @user.blank?       @chk=User.where(:username=>params[:user][:username]).pluck(:role)[0]       @chk1=User.where(:username=>params[:user][:username]).pluck(:block_status)[0]       if @chk=="Admin"          if @chk1==nil           session[:user_id]=@user.first.id           redirect_to :action=>"admin_page"         else           flash[:notice] = "sorry!... Administrator blocked you..."           redirect_to root_path         end       elsif @chk=="user"         redirect_to root_path       elsif @chk==nil         redirect_to :action=>"client_page"       end     else       flash[:notice] = "Enter valid username and password"        redirect_to root_path     end     end  end  

My Application controller,

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    before_action :check_session    def check_session      if session[:user_id].blank?        redirect_to root_path      end    end  end  

No comments:

Post a Comment