has_one with many to many table architecture Posted: 12 Apr 2016 07:01 AM PDT Is it possible to have a has_one relation between tables connected through a many-to-many table? By default it raises an exception on a missing foreign_key in the child table. Just as an example: class Car < ActiveRecord::Base has_and_belongs_to_many :roads_travelled, class_name: 'Road' has_one :last_road_travelled, {order{travelled_at.desc}.limit(1)}, class_name: 'Road' end |
How to transaparently use finders on in-memory collections or in-database collections? Posted: 12 Apr 2016 06:46 AM PDT I have a model List , which has_many :members . It has a method member? which must work on collections which are persisted in the database as well as in-memory collections. class List < ActiveRecord::Base has_many :members, inverse_of: :list def memory_member?(user) members.find { |m| m.user == user }.present? end def eager_loaded_member?(user) members.includes(:user).find { |m| m.user == user }.present? end def scoped_member?(user) members.where(user_id: user.id).present? end def member?(user) # Which to choose, or how to switch? end end class Member < ActiveRecord::Base belongs_to :user end When I call this on a stored set of members this works fine. But I want to use #member? for both in-memory and in-database collections: user = User.new member_w_user = Member.new(user: user) member_wo_user = Member.new list = List.new(members: [member_w_user, member_wo_user]) list.member?(user) #=> true list.save user.persisted? #=> true list.member?(user) #=> true The problem is that with the includes(:user) and where the searcher works only on stored collections. And without the includes, it works for both, but has severe database performance degradation[1]. How can I use helpers like includes , where or other such database-selectors transparently alongside in-memory finders? So that I have one method member? that works both on stored collections, and leverages the database, and on on-memory collections by falling back on simple Enum/Array finders. -- [1] This is the reason why I am adding it in the first place: to avoid some heavy N+1 Queries. |
How to validate overlapping times in Rails with postgresql Posted: 12 Apr 2016 06:44 AM PDT I have an Event model that has start_at time and end_at time in my schedule app and I want to validate the overlapping time before saving. I create my rails app on Cloud9. My view image as followings; Day1 07:00 - 07:20 event1 10:30 - 11:30 event2 15:40 - 16:10 event3 [add event button] Day2 08:15 - 09:05 event4 12:08 - 13:04 event5 14:00 - 14:25 event6 [add event button] [save schedule button] start_at time and end_at time can be changed and added at the same time. What I'd like to do is to display error if I try to add (or change to) 07:05 - 07:30 for Day1 , for example, 13:50 - 14:30 for Day2 and so on. For example; app_development=# select * from events; id | start_at | end_at | title | detail | schedule_id | created_at | updated_at ----+----------+----------+--------+--------+-----------------+----------------------------+---------------------------- 1 | 07:00:00 | 07:20:00 | event1 | | 1 | 2016-04-12 05:28:44.166827 | 2016-04-12 12:52:07.682872 2 | 10:30:00 | 11:30:00 | event2 | | 1 | 2016-04-12 05:28:44.17747 | 2016-04-12 12:52:07.689934 3 | 15:40:00 | 16:10:00 | event3 | | 1 | 2016-04-12 05:29:07.5005 | 2016-04-12 12:52:07.693477 I added 07:05 - 07:30 above table, but the validation doesn't work. Although I asked the similar question, I was advised to use postgresql instead of sqlite3. So I managed to configure postgresql, but the result is the same. It would be appreciated if you could give me how to check and display error. schema.rb create_table "events", force: :cascade do |t| t.time "start_at" t.time "end_at" t.string "title" t.integer "room_id" ... create_table "rooms", force: :cascade do |t| t.string "room" t.integer "schedule_id" ... create_table "schedules", force: :cascade do |t| t.string "title" t.integer "user_id" t.date "departure_date" ... Give the following models: class Event < ActiveRecord::Base belongs_to :room, inverse_of: :events has_one :schedule, autosave: false, through: :room ... validate :cannot_overlap_another_event def cannot_overlap_another_event range = Range.new start_at, end_at overlaps = Event.exclude_self(id).in_range(range) overlap_error unless overlaps.empty? end scope :in_range, -> range { where('(start_at BETWEEN ? AND ?)', range.first, range.last) } scope :exclude_self, -> id { where.not(id: id) } def overlap_error errors.add(:overlap_error, 'There is already an event scheduled in this hour!') end class Schedule < ActiveRecord::Base belongs_to :user has_many :rooms, inverse_of: :schedule accepts_nested_attributes_for :rooms, allow_destroy: true ... class Room < ActiveRecord::Base belongs_to :schedule, inverse_of: :rooms has_many :events, inverse_of: :room accepts_nested_attributes_for :events, allow_destroy: true ... _schedule_form.html.erb <%= render 'shared/error_messages', object: f.object %> <%= f.label :title %> <%= f.text_field :title, class: 'form-control' %> <br> <%= f.label :departure_date %> <div class="input-group date" id="datetimepicker"> <%= f.text_field :departure_date, :value => (f.object.departure_date if f.object.departure_date), class: 'form-control' %> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> <script type="text/javascript"> $(function () { $('#datetimepicker').datetimepicker({format:'YYYY-MM-DD'}); }); </script> <br> <div id="room"> <%= f.simple_fields_for :rooms do |a| %> <div id="room_<%= a.object.object_id %>"> <p class="day-number-element-selector"><b>Day <%= a.index.to_i + 1 %></b></p> <%= a.simple_fields_for :events do |e| %> <span class="form-inline"> <p> <%= e.input :start_at, label: false %> - <%= e.input :end_at, label: false %> </p> </span> <%= e.input :title, label: false %> <% end %> </div> <%= a.link_to_add "Add event", :events, data: {target: "#room_#{a.object.object_id}"}, class: "btn btn-primary" %> <%= a.input :room %> <% end %> </div> It would be appreciated if you could give me how to check and display error. |
how to install gem acts_as_reviewable in rails 4 Posted: 12 Apr 2016 06:56 AM PDT I try install gem 'acts_as_reviewable' in my project. In my Gemfile gem 'acts_as_reviewable' #gem 'acts_as_reviewable', github: 'edshadi/acts_as_reviewable' Gemfile.lock acts_as_reviewable (0.0.1) After 'bundle install' When to generate reviewable rails g acts_as_reviewable_migration #or rails g review:acts_as_reviewable_migration So error: Could not find generator 'review:acts_as_reviewable_migration'. Maybe you meant 'acts_as_reviewable_migration', 'active_record:migration' or 'acts_as_commentable_upgrade_migration' Run rails generate --help for more options When i run rails g --help #=> ActsAsReviewableMigration: acts_as_reviewable_migration So, how to fix this error. And please recommend to me a gem same gem reviewable, can use it in rails 4. |
DatatypeMismatch: ERROR: argument of AND must be type boolean, not type integer Posted: 12 Apr 2016 06:38 AM PDT Following code is running fine on local machine , but causing issue on heroku live server. Showing following and title error. NoMethodError (undefined method `attributes') def user_view_history user_views = Array.new logs = ViewsLog.where(:user_id=>@user.id).select(:unit_id,:unit_type).distinct logs.each do |log| if log.unit_type == "Ad" #if unit_type is Ad if Ad.exists?(log.unit_id) ad = Ad.find(log.unit_id) user_views << ad else ViewsLog.where(unit_id:log.unit_id).destroy_all end else # for survey if Survey.exists?(log.unit_id) survey = Survey.find(log.unit_id) user_views << survey else ViewsLog.where(unit_id:log.unit_id).destroy_all end end end user_history = user_views.paginate(page: params[:page], per_page: 8) render json: {:success=>true, :message=>"List of User History",:user_history=>user_history.map{ |u| u.attributes.merge("thumbnail_url" => "https://#{Rails.configuration.aws[:complete_region]}/#{Rails.configuration.aws[:bucket]}/#{u.campaign.campaign_type}/Images/#{u.thumbnail_uniqee_id}/#{u.thumbnail_file_name}","campaign_type" => u.campaign.campaign_type )} }, :status=>200 end |
The script is not called in application.js.coffee Posted: 12 Apr 2016 06:41 AM PDT I have view: .form-actions %p= attach_links = f.button :submit, 'Add post', class: 'btn-bg' - if paid? = f.button :submit, 'save in ...', class: 'btn-inverse', name: 'draft' = button_tag 'Add poll', type: 'button', id: 'poll-btn', class: 'btn btn-bg' = link_to 'Cancel', blog_posts_path When click button_tag 'Add poll' will display form for new Poll. Its my script in app/assets/javascript/application.js.coffee for display form new poll: $(document).ready -> $('#poll-btn').click -> if $('.poll').is(':visible') $('.poll').hide() $('#poll-btn').text 'Add poll' event.preventDefault() else $('.poll').show() $('#poll-btn').text 'Delete Poll' event.preventDefault() return return GEMFILE group :assets do gem 'sass-rails' gem 'coffee-rails' gem 'compass-rails' gem 'bootstrap-sass', '2.1.1.0' gem 'therubyracer' gem 'execjs' gem 'uglifier', '>= 1.0.3' gem 'oily_png' # gem 'font-awesome-rails' gem 'turbo-sprockets-rails3' end I click on button, but dont call my script. I cant undestand why. Can you help me solve this issue? Thank you. EDIT part of application.js.coffee $(document).on 'click', '@load_more_comments', (e) -> e.preventDefault() $(this).html("<i class='icon icon-spin icon-refresh'></i> загрузка...") u = $(this).parent().find('@comments_list').data('u') l = $(this).parent().find('@comments_list').data('lastcid') $.ajax url: u dataType: 'script' method: 'GET' data: loadnew: l $(document).ready -> $('#poll-btn').click -> if $('.poll').is(':visible') $('.poll').hide() $('#poll-btn').text 'Add poll' event.preventDefault() else $('.poll').show() $('#poll-btn').text 'Delete poll' event.preventDefault() return return show_photo = (u) -> if window.innerWidth > 780 $.fancybox.showLoading() $.ajax url: u method: 'GET' dataType: 'script' data: w: window.innerWidth h: window.innerHeight else document.location = u |
Rails Controller - param is missing or the value is empty: booking (Stripe Integration) Posted: 12 Apr 2016 06:35 AM PDT I'm trying to complete a Stripe.js integration into my Rails app for an event booking site and I'm getting the error above. I've looked at lots of similar issues on here and none of the solutions seem to work. Here's my code - Bookings Controller class BookingsController < ApplicationController before_action :booking_params, only: [:create] before_action :authenticate_user! def new # booking form # I need to find the event that we're making a booking on @event = Event.find(params[:event_id]) # and because the event "has_many :bookings" @booking = @event.bookings.new # which person is booking the event? @booking.user = current_user end def create # actually process the booking @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) @booking.user = current_user if @booking.save # CHARGE THE USER WHO'S BOOKED # #{} == puts a variable into a string Stripe::Charge.create(amount: @event.price, currency: "gbp", card: @booking.stripe_token, description: "Booking number #{@booking.id}") flash[:success] = "Your place on our event has been booked" redirect_to event_path(@event) else flash[:error] = "Payment unsuccessful" render "new" end end private def booking_params params.require(:booking).permit(:stripe_token) end end booking model class Booking < ActiveRecord::Base belongs_to :event belongs_to :user end Booking view - <%= simple_form_for [@event, @booking] do |form| %> <span class="payment-errors"></span> <div class="form-row"> <label> <span>Card Number</span> <input type="text" size="20" data-stripe="number"/> </label> </div> <div class="form-row"> <label> <span>CVC</span> <input type="text" size="4" data-stripe="cvc"/> </label> </div> <div class="form-row"> <label> <span>Expiration (MM/YYYY)</span> <input type="text" size="2" data-stripe="exp-month"/> </label> <span> / </span> <input type="text" size="4" data-stripe="exp-year"/> </div> <%= form.button :submit %> <% end %> <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript"> // This identifies your website in the createToken call below Stripe.setPublishableKey('<%= STRIPE_PUBLIC_KEY %>'); // ... // jQuery(function($) { - changed to the line below $(document).on("ready page:load", function () { $('#new_order').submit(function(event) { var $form = $(this); // Disable the submit button to prevent repeated clicks $form.find('input[type=submit]').prop('disabled', true); Stripe.card.createToken($form, stripeResponseHandler); // Prevent the form from submitting with the default action return false; }); }); var stripeResponseHandler = function(status, response) { var $form = $('#new_order'); if (response.error) { // Show the errors on the form $form.find('.payment-errors').text(response.error.message); $form.find('input[type=submit]').prop('disabled', false); } else { // token contains id, last4, and card type var token = response.id; // Insert the token into the form so it gets submitted to the server $form.append($('<input type="hidden" name="order[stripe_token]" />').val(token)); // and submit $form.get(0).submit(); } }; </script> For some reason its not capturing the booking_params. Any advice or guidance would be appreciated. |
Rails/Sendgrid Error: getaddrinfo: name or service not known Posted: 12 Apr 2016 06:13 AM PDT I've all of a sudden started getting this error when creating users in my app. Emails were working before I left for vacation, now I come back and this is what my tech support gives me! Ugh. So, I make a user, and I get redirected to my admin panel with the following error in a flash notice: getaddrinfo: name or service not known . The user isn't created. Looking at the logs, it looks like everything worked fine: I, [2016-04-12T08:01:52.089647 #11555] INFO -- : Started POST "/admin/user/new" for 72.238.202.193 at 2016-04-12 08:01:52 -0500 I, [2016-04-12T08:01:52.092114 #11555] INFO -- : Processing by RailsAdmin::MainController#new as HTML I, [2016-04-12T08:01:52.092259 #11555] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"vxhuTwXhQo6nYrskQcYH9W56Ej95LgzEbs8cnkjXQI4=", "user"=>{"company_id"=>"35", "username"=>"myuser@thedomain.com", "first_name"=>"Test", "last_name"=>"User", "full_name"=>"Test User", "time_zone"=>"Central Time (US & Canada)", "email"=>"myuser@thedomain.com", "phone_number"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "reset_password_sent_at"=>"[FILTERED]", "remember_created_at"=>"", "sign_in_count"=>"0", "current_sign_in_at"=>"", "last_sign_in_at"=>"", "current_sign_in_ip"=>"", "last_sign_in_ip"=>"", "authentication_token"=>"", "enable_notifications"=>"1", "confirmation_token"=>"MBrmpsD6Wtf1VBrhtDyc", "confirmed_at"=>"", "confirmation_sent_at"=>"April 12, 2016 10:00", "unconfirmed_email"=>"myuser@thedomain.com", "terms_accepted"=>"1", "cancel_subscription"=>"0", "on_trial"=>"0", "is_account_owner"=>"1", "role_ids"=>["", "", "2"]}, "return_to"=>"https://www.myserver.com/admin/user?sort=created_at&sort_reverse=false", "_save"=>"", "model_name"=>"user"} I, [2016-04-12T08:01:52.212064 #11555] INFO -- : Rendered devise/mailer/confirmation_instructions.html.erb (1.6ms) I, [2016-04-12T08:01:52.340343 #11555] INFO -- : Sent mail to myuser@thedomain.com (9.3ms) I've filtered the email address but, rest assured, it's a valid email. I'm using EC2 to host my application, so I can't edit /etc/resolv.conf since any changes will be overridden. I've run nslookup to make sure the server can find the domain MX records, which it does using the nameserver specified in /etc/resolv.conf . What else can I do to troubleshoot this issue? |
Rails Referenced Models - undefined method `updated?' Posted: 12 Apr 2016 06:02 AM PDT I have the following models members(id, name, company_id, ...) companies(id, name, created_by,...) I have the following associations Member Model class Member < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable acts_as_paranoid attr_accessor :company_name # Associations belongs_to :company has_one :company, class_name: 'Company', foreign_key: 'created_by' # Methods after_create :create_company1 def create_company1 self.create_company(name: company_name, time_zone_name: 'asdas', status: 1, company_type: 'brand') end end Company Model class Company < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged acts_as_paranoid # Associations has_many :members, dependent: :destroy belongs_to :owner, class_name: "Member", foreign_key: 'created_by' end When i try to create an account the following should happen - Create a record in Members table with company_id blank
- Create a company record with created_by = member from step 1
- Update the record in Step 1 with company id from step 2.
I am getting the following error NoMethodError at /members undefined method `updated?' for #<ActiveRecord::Associations::HasOneAssociation:0x007fd70a3d2988> |
Translate role name in hash Posted: 12 Apr 2016 06:06 AM PDT In users model I add role: Roles = [:registered, :banned, :admin ] def is?( requested_role ) self.role == requested_role.to_s end How I can translate role name in veiw? |
Changing f.select to checkbox Posted: 12 Apr 2016 05:39 AM PDT I have the following in my view at which the can select several categories: <%= form_for(@survey) do |f| %> Categories <br> <%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %><br> <%= f.submit %> <% end %> I want the user to be selecting the categories with checkboxes instead of drop down list. I am not sure how this is possible. Two parts: 1. How it will display several checkboxes and 2. How it will be saving the user's selections as it is saving fine for the f.select above. The approach (which is not complete) that I though of is to iterate through the categories and add a checkbox for each category. However I am not sure if this will make sure that the several selections will be saved. <% @categories.each do |category| %> <%= category.name %><br> <%= f.check_box :category_ids %> Any guidance/tip to the right direction is greatly appreciated. |
cocoon gem can't remove nested field image Posted: 12 Apr 2016 05:30 AM PDT I have set up the cocoon gem correctly and everything is working fine, I can upload images as required but when I click remove, it does not seem to remove the image. Here is my code: _image_fields.html.erb <div class="nested-fields"> <%= f.text_area :description %> <%= f.file_field :picture %> <%= link_to_remove_association "remove", f %> </div> here is my form: <div class="imagefield"> <h2>Images</h2> <h4>upload images</h4> <hr> <div class="customgap"> <div class="images"> <%= f.fields_for :images do |image| %> <%= render 'image_fields', f: image %> <% end %> <div class="links"> <%= link_to_add_association 'add image', f, :images %> </div> </div> </div> </div> |
Internal server error with ruby on rails Posted: 12 Apr 2016 06:53 AM PDT Trying to make this ajax call work.But I get the 500 Internal server error. Updated: Script.js $.ajax({ type: "GET", url: '/books/103/last_chapter.json', success: function(data) { $("body").append(data); }, error: function(xhr, status, response) {console.log('response ' + response + ' , xhr' + xhr + ' , ' + 'STATUS ' + status)} }); Chapter controller: def last_chapter Chapter.order(created_at: :desc).limit(1) respond_to do |format| format.js end end config.routes resources :books do member do get '/last_chapter/', to: 'chapters#last_chapter', as: 'last_chapter' end resources :chapters end How the route looks in the terminal: last_chapter_book GET /books/:id/last_chapter(.:format)chapters#last_chapter The error in terminal Started GET "/books/103/last_chapter" for 127.0.0.1 at 2016-04-12 14:17:37 +0200 Processing by ChaptersController#last_chapter as */* Parameters: {"id"=>"103"} Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.0ms) ActionView::MissingTemplate (Missing template chapters/last_chapter, application/last_chapter with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/Users/namek/myrails/app/views" ): app/controllers/chapters_controller.rb:28:in `last_chapter' last_chapter.json json.extract! @last_chapter, :id, :title, :characters, :created_at, :updated_at |
Searchkick index blob columns Posted: 12 Apr 2016 05:21 AM PDT I'm trying to use Searchkick gem to provide full text search for a blob column in MySQL database, the column has text data stored in binary format, will become readable when using Zlib.inflate(model_column) function. Is there is a way to perform data conversion before passing it to searchkick? Adding searchkick to other models in my application works, only when indexing blob column, I get this error Events.first.reindex Events Load (0.5ms) SELECT `events`.* FROM `events` LIMIT 1 Events Store (3.4ms) {"id":"","exception":["Encoding::UndefinedConversionError","\"\\x9C\" from ASCII-8BIT to UTF-8"]} Encoding::UndefinedConversionError: "\x9C" from ASCII-8BIT to UTF-8 |
What's the difference between a Voter and Follower in Ruby On Rails? [on hold] Posted: 12 Apr 2016 05:13 AM PDT I'm deciding polymorphic associations/gems I need to use. I was using acts_as_follower, but then I needed some voting mechanism for another model in my app, so I'm thinking of using acts_as_voteable. I also realized that I could use them gem also for the follower model I used before. I'm still in development, so I can change models etc. Is there any reason to keep them separate? Any advice would be greatly appreciated. |
Google chrome: Http request is not hitting to server Posted: 12 Apr 2016 05:02 AM PDT Sometimes while browsing my website i am not able to get any response from server. in the network tab of chrome console it shows status of request as "pending". i waited for half an hour but still the status of request was pending. i checked the log file of the nginx server and found that request is not hitting to server at all. it means browser is not able to reach to server. After clearing the browser cache everything was working fine and i was able to get response from the server but after some half an hour this issue came again. i want to know why the browser cache not allowing http request to reach to server. |
Subdomain not working with Devise Routes Posted: 12 Apr 2016 05:15 AM PDT I have the following routes constraints :subdomain => "brands" do scope :module => "brands", :as => "brands" do devise_for :members # devise_for :users, controllers: { # sessions: 'users/sessions' # } end end When i go to http://brands.lvh.me:3000/members/sign_up i am getting the following error ActionController::RoutingError at /members/sign_up uninitialized constant Brands::RegistrationsController Application Frames All Frames ActionDispatch::Routing::RouteSet::Dispatcher#controller actionpack (4.2.5.2) lib/action_dispatch/routing/route_set.rb, line 63 Registration Controller - `app/controllers/brands/members/registrations_controller.rb class Brands::Members::RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /resource # def create # super # end # GET /resource/edit # def edit # super # end # PUT /resource # def update # super # end # DELETE /resource # def destroy # super # end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. # def cancel # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_up_params # devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) # end # The path used after sign up. # def after_sign_up_path_for(resource) # super(resource) # end # The path used after sign up for inactive accounts. # def after_inactive_sign_up_path_for(resource) # super(resource) # end end |
Rails_admin accepts_nested_attributes for has_many restrict validation Posted: 12 Apr 2016 04:45 AM PDT I'm using rails_admin , Product model has_many gallery. In product model I've added accepts_nested_attributes_for :galleries, :allow_destroy => true for nested form but if I add the galley of image(validation : presence => true) to product and in the same form I remove that image by clicking red trash button, it just removes the image but that form will be there (you can see in the screenshot as "Product Gallery New") and when I click on the save button it won't create the product because of that validation in gallery, without removing the validation how can I handle this? check the screenshot. |
I need a refresh before my redirection, why? Posted: 12 Apr 2016 05:04 AM PDT I'm doing a web app, and this night, I try to make a preview of the upload image of my post.Like in the photo : before|| After And since that, I have to refresh my :edit and :new page post. If I don't do that, the page is frozen ! views/posts/_form : <div class= "posts-wrapper"> <div class= "post"> <div class= "post-body"> <div class= "image-wrap"> <%= image_tag 'placeholder.jpg', id: 'image-preview', class: 'img-responsive' %> <%= simple_form_for @post, html: { multipart: true } do |f| %> </div> <div class= "row"> <div class= "col-md-12.text-center"> <%= f.error_notification %> </div> <div class= "container-fluid"> <div class= "form-group.text-center"> <h4> Upload an image (this is required): </h4> <%= f.input :image, label: false, input_html: { onChange: 'loadFile(event)' } %> </div> <div class= "form-group.text-center"> <%= f.input :caption, label: false, placeholder: 'Add your caption' %> </div> <div class= "form-group.text-center"> <%= f.button :submit, class: 'btn-success btn-block' %> </div> </div> </div> </div> </div> <%end%> </div> assets/js/posts.js : var loadFile = function(event) { var output = document.getElementById('image-preview'); output.src = URL.createObjectURL(event.target.files[0]); }; And the helpers/appli : def form_image_select(post) return image_tag post.image.url(:medium), id: 'image-preview', class: 'img-responsive' if post.image.exists? image_tag 'placeholder.jpg', id: 'image-preview', class: 'img-responsive' end How I can solve this problem ? I try a lot of things, even an automatic refresh of the page when the user is arriving, but it's so dirty ! |
Rails + Jasmine-Ajax: what is the correct way to test code triggered by `ajax:success` (jquery-ujs) Posted: 12 Apr 2016 04:30 AM PDT I am trying to test a certain internal library that has some JS behavior triggered on the ajax:success event. The library creates a link that looks like this: <%= link_to 'click here', '/some_path', class: 'special-link', remote: true %> And in the JS part of the library there is event binding code, which is the part I want to black-box test through its effect on the DOM: $(document).on 'ajax:success', '.special-link', (e, data, status, xhr) -> # Code that has some effect on the DOM as a function of the server response The library works as expected in the browser. However, when I try to test the library in Jasmine by calling $('.special-link').click() , the desirable effect on the DOM cannot be observed. The issue, it seems, is that the ajax:success event does not get triggered: describe 'my library', -> beforeEach -> MagicLamp.load('fixture') # Fixture library that injects the link above to the DOM jasmine.Ajax.install() jasmine.Ajax.stubRequest('/some_path').andReturn({ responseText: 'response that is supposed to trigger some effect on the DOM'}) afterEach -> jasmine.Ajax.uninstall() # Works. The fixtures are loading properly it '[sanity] loads fixtures correctly', -> expect($('.special-link').length).toEqual(1) # Works. The jquery-ujs correctly triggers an ajax request on click it '[sanity] triggers the ajax call', -> $('.special-link').click() expect(jasmine.Ajax.requests.mostRecent().url).toContain('/some_path') # Works. Code that tests a click event-triggering seems to be supported by Jasmine it '[sanity] knows how to handle click events', -> spy = jasmine.createSpy('my spy') $('.special-link').on 'click', spy $('.special-link').click() expect(spy).toHaveBeenCalled() # Does not work. Same code from above on the desired `ajax:success` event does not work it 'knows how to handle ajax:success events', -> spy = jasmine.createSpy('my spy') $('.special-link').on 'ajax:success', spy $('.special-link').click() expect(spy).toHaveBeenCalled() What is the right way to test the effect on the DOM of code that runs in ajax:success events? |
Rails db:migrate / db:create. Existed databases conflict Posted: 12 Apr 2016 05:37 AM PDT I previously was making some webapps using Spring MVC + PostgreSQL on my PC. Wanted to try RoR, faced strange prob with DB connection, google isn't helping. I created i new Rails web-application, made one model and tried to make a migration. (Last Rails gem, 5.0.0.beta3) The problem is: When i'm running db:migrate/create/drop Rails is trying to manipulate my existing DB's instead of creation new ones. -i have a few PostgreSQL databases on my local PostgreSQL server, which i still want to keep active on it. Lets say 'XXXXXXX', 'YYYYYYYYY', 'ZZZZZZZZZ' Once i run db:create i get the following log: C:\Users\****\RubymineProjects\sample_articles>rails db:create 'XXXXXXX' already exists DB migrate is executed successfully and also creating one additional database 'sample_articles_development', which is the name as i specify in my database.yml . BUT the new tables appears to my existed database 'XXXXXXX'(which i didn't configure in any configs). This is my database.yml config: default: &default adapter: postgresql encoding: unicode # For details on connection pooling, see rails configuration guide # http://guides.rubyonrails.org/configuring.html#database-pooling pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default database: sample_articles_development username: rails password: ******* host: localhost port: 5432 test: <<: *default database: sample_articles_test production: <<: *default database: sample_articles_production username: sample_articles password: <%= ENV['SAMPLE_ARTICLES_DATABASE_PASSWORD'] %> |
OR Condition in Scope Rails Posted: 12 Apr 2016 04:23 AM PDT In my prescription.rb model, I have written the following working scope Note that: prescription has_many patient_prescriptions scope :undeleted_prescriptions, -> { includes(:patient_prescriptions).where(patient_prescriptions: { is_deleted: false })} Now I want it to return also those records where is_deleted: nil e.g. all record where is_deleted is false or nil |
Why is my form: parameter not linking a select box to the correct form in Rails? Posted: 12 Apr 2016 04:16 AM PDT I'm using form_tag in Rails to build a form within a table: <%= form_tag('/sale_qualifiers', :id => 'new_sale_qualifier', :class => 'form', method: :post, remote: true, data: { model: "sale_qualifier" }) do -%> I then link the fields created back to the correct form using the following <%= answer.text_area :answer_text, :placeholder => "Enter your answer", form: "new_sale_qualifier"%> Which works great for answers that belong in a text_area or text_field but stops working with select elements for some reason. As an example, the output of the text_area code above (in HTML) is: <textarea placeholder="Enter your answer" name="sale_qualifier[answer_attributes][answer_text]" id="sale_qualifier_answer_attributes_answer_text" form="new_sale_qualifier"></textarea> Which is linked to the form. Whereas the output of: <%= answer.select :answer_text, [['Yes', true], ['No', false]], form: "new_sale_qualifier"%> Is: <select id="sale_qualifier_answer_attributes_answer_text" name="sale_qualifier[answer_attributes][answer_text]"> <option value="true">Yes</option> <option value="false">No</option> </select> This is then not submitting my answer_attributes when I click the associated submit button. It doesn't matter whether I pass options or not, I can never get the select element to bind to the right form. I guess I could add this on load using a Jquery call, but that seems a bit hacky. Is there a reason why select elements don't take the form: info in ERB? |
Openshift rack 1.5.2 and 1.6.4 Posted: 12 Apr 2016 04:16 AM PDT Well-known issue " You have already activated rack 1.5.2, but your Gemfile requires rack 1.6.4" But why when I try to use simple Gemfile source 'https://rubygems.org' gem 'sinatra' I can easy find error proactively: vi .openshift/action-hooks/deploy cd $OPENSHIFT_REPO_DIR bundle show Gems included by the bundle: Could not find rack-1.6.4 in any of the sources Clear. Same way this are rails, Gemfile contains ..... gem 'rake', '0.9.6' I obtain Gems included by the bundle: Could not find rake-0.9.6 in any of the sources gem list for gear shows: ... rake (0.9.6) Anycase, gem install rack -v '1.6.4' solves problem with HTTP 500. I cann't understand why? |
Rails redirect scoped routes Posted: 12 Apr 2016 04:08 AM PDT I have an app with the following scoped routes: scope "(:locale)", :locale => Regexp.new(I18n.available_locales.join('|')) do # ... # lots of routes here # ... end As you can see, the 'locale' is optional here. Both http://myapp.com/en/foo and http://myapp.com/foo end up to the same controller#action. Works great. Now I want to get rid of the locale in the url, but I want old routes still to work, so simply removing the scope statement won't do. I'd like to redirect old locale based url to be redirected to the non-locale url. Like this: http://myapp/en/foo redirect to http://myapp/foo and http://myapp/foo still to work as it used to do. So far, I only found a 'redirect' option in the Rails guides for individual routes. But I'd like this to hold for a collection of routes; the routes in my 'scope' block. Any ideas on how to get this working? |
Rails has_one association expected Model got String Posted: 12 Apr 2016 05:30 AM PDT Having the following associations between 3 models: workout.rb class Workout < ActiveRecord::Base has_and_belongs_to_many :workout_sets, :join_table => :workout_sessions belongs_to :warmup, :class_name => :WorkoutStep, :foreign_key => "workout_step_id" accepts_nested_attributes_for :workout_sets, allow_destroy: true accepts_nested_attributes_for :warmup, allow_destroy: true end workout_set.rb class WorkoutSet < ActiveRecord::Base has_and_belongs_to_many :workout_steps, :join_table => :sets_steps, dependent: :destroy has_and_belongs_to_many :workouts, :join_table => :workout_sessions accepts_nested_attributes_for :workout_steps, allow_destroy: true has_one :intro_video_usage, class_name: 'VideoUsage::Intro', as: :parent, dependent: :destroy has_one :intro_video, through: :intro_video_usage, source: :video accepts_nested_attributes_for :intro_video has_one :get_ready_video_usage, class_name: 'VideoUsage::GetReady', as: :parent, dependent: :destroy has_one :get_ready_video, through: :get_ready_video_usage, source: :video has_one :congrats_video_usage, class_name: 'VideoUsage::Congratulations', as: :parent, dependent: :destroy has_one :congrats_video, through: :congrats_video_usage, source: :video end and workout_step.rb class WorkoutStep < ActiveRecord::Base has_and_belongs_to_many :workout_sets, :join_table => :sets_steps has_many :main_video_usage, class_name: 'VideoUsage::Main', as: :parent has_many :main_videos, through: :main_video_usage, source: :video accepts_nested_attributes_for :main_videos end And using simple_form and cocoon to handle nested models creation on the top level model (Workout ) I'm having troubles building the form for sets and steps - more concise, when associating a workout_set with an intro_video (and whitelisting the params) I'm having the following error: Video(#70285207226600) expected, got String(#70285080848240) The params object after sending looks like this: "workout"=>{"title"=>"", "workout_sets_attributes"=>{"0"=>{"_destroy"=>"false", "intro_video"=>"70", "title"=>""}}}, "image"=>"", "sound_logo"=>"", "intro_video"=>"", "commit"=>"Create workout"} Thanks in advance. |
Implement authorization for ActiveRecord methods Posted: 12 Apr 2016 04:28 AM PDT I've been trying to implement an authorization layer on top of ActiveRecord. Let me explain how that is supposed to work. Databases Consider a database table Invoices with the following fields - InvoiceId
- CustomerId
- ... other fields
There will be an auxiliary table InvoicePrivileges with the fields - ObjectId (referring to an invoice id)
- SubjectId (referring to a customer id in this case)
- Subject type (to handle multiple kinds of users - customer, admin, operator, etc)
- Read (boolean)
- Write (boolean)
Authorization checks To be able to read an invoice, the entity attempting to read the row or set of rows must have a set of entries in the InvoicePrivileges table (where InvoicePrivileges.object_id refers to an InvoiceId ) with InvoicePrivileges.read = true . Example, a query to fetch a bunch of invoices from the DB SELECT invoice.* FROM Invoices invoice LEFT JOIN InvoicePrivileges privilege ON invoice.invoice_id = privilege.object_id AND privilege.subject_id = <user_id> AND privilege.subject_type = <user_type> WHERE privilege.read = TRUE; The same condition applies when trying to update an invoice, except the last WHERE condition becomes WHERE privilege.write = true . Implementation I can use the Arel library to create these constraints with ease. However, where do I implement these methods in such a way that all ActiveRecord save and update actions include these constraints? I don't mind writing a bit of code to enable this. I'm looking for pointers as to how best to go about it. |
Ruby layout not loading while calling render Posted: 12 Apr 2016 04:08 AM PDT I am using model validation I want to load the default layout with register.html.erb page. But while i am using rendering only register my layout not loading. Please check - #users_controller.rb def create @user = User.new(create_user_params) #raise @user.inspect respond_to do |format| if @user.save format.html { redirect_to :success, notice: 'Registration was successfully created.' } format.json { render :success, status: :created, location: @users } else format.html { render :register } format.json { render json: @users.errors, status: :unprocessable_entity } end end end Here is format.html { render :register } I have successfully getting my validating error message. But design missing only loading register.html.erb . Complete page not coming with layout.If I am using redirect_to :register instead of render :register my page redirect successfully to register page but my error message not showing. How I will showing both my validating error and design? users_controller.rb class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :destroy, :register_success] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end #=============================CHINU CODE START def login @title = 'Login' render layout: 'login' end def create_login user = User.authenticate(params[:user][:username], params[:user][:password]) if user log_in @user redirect_to @user else flash[:danger] = 'Invalid email/password combination' # Not quite right! redirect_to :back end end def register @user = User.new @title = 'Register' render layout: 'login' end def create @user = User.new(create_user_params) #raise @user.inspect respond_to do |format| if @user.save format.html { redirect_to @users, notice: 'Registration was successfully created.' } format.json { redirect_to :success, status: :created, location: @users } else format.html { render :register } format.json { render json: @users.errors, status: :unprocessable_entity } end end end def register_success raise @user.inspect end def check_email email = params[:user] user = User.where("email = ?", email).first if user.present? render :json => [false , "This email is already taken"] else render :json => [true , "Email available"] end end def check_username username = params[:user] user = User.where("username = ?", username).first if user.present? render :json => [false , "Username has already been taken"] else render :json => [true , "Username available"] end end #=============================CHINU CODE END private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:name, :username, :email, :password, :image, :dob, :photo, :address) end def create_user_params params.require(:user).permit(:name, :username, :email, :password, :dob, :address) end def login_user_params params.require(:user).permit(:username, :password, :password_confirmation) end end application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper end |
Has many through: How to Add record and fill fields in join table Posted: 12 Apr 2016 05:32 AM PDT I have these models: class Item < ActiveRecord::Base has_many :users, through: :user_items has_many :user_items end class User < ActiveRecord::Base has_many :items, through: :user_items has_many :user_items end class UserItem < ActiveRecord::Base belongs_to :user belongs_to :item end create_table "user_items", force: :cascade do |t| t.integer "user_id", t.integer "item_id", t.integer "amount" end I'd like to know the best ways to add an item to a user an also set an amount in the join table. I was doing something like this: user = User.first item = Item.first UserItems.create(user: user, item: item, amount: 5) but I don't like it so much, and sometimes it doesn't work properly, because if I run user.items #=> [] I get empty array, it seems like it doesn't get the new changes in DB. So, is there an easy way to do that? something intuitive like this would be perfect: user.user_items << item, amount: 4 Ok, so I did this way and it worked: user.user_items.create!(item: item, amount: 5) But This way it didn't: user.user_items << item, amount: 4 Now it's more elegant. But I still have the problem about the caching request. If I run user.items. it is still empty. Any idea? I tried with inverse_of and nothing. I would like to avoid reload or some methods like this. I would like to do in a transparent way, if it is possible |
how to build an version API for an existing rails app? Posted: 12 Apr 2016 04:48 AM PDT how to build a version API for an existing rails app? i have built a simple app with relation ship of User and company Company has_many users User belongs_to company how can i build a versioned api for this app |
No comments:
Post a Comment