How to make changes made by javascript persistent (rails) Posted: 05 May 2016 06:45 AM PDT I'm trying to make changes made by javascript persistent. Specifically, I have a rails app which allows a user to "like" other users' posts. When the user likes (faves) a post, or when a new favorite is created, I want the background colour of the post to change (say, to green ) using javascript and/or jQuery (I could not see any other way to do this). The problem is that when I reload the page the change is not persistent, with the background colour turning into the default one. I've tried the following, none of which worked; addClass in combination with removeClass append the <style> ... </style> tags directly so the changes in styling can be persistent, without success. I've tried the above both in app/views/favorites/create.js.erb and directly in the view template where faved posts appear using <script> ... </script> tag. Any suggestions will be greatly appreciated. |
Rails skip byebug(s) for the rest of the execution Posted: 05 May 2016 07:00 AM PDT I am using inline byebug to stop the program execution and debug, from rails console or from a running rails server. I have to debug a very repetitive loop, and I need to put a byebug in the middle of that loop. After debugging, it seems my options are either to keep pressing c until I can get out of my loop, or abort the console execution execution with exit or something similar. But then I need to reload the whole environment. Is it possible to just tell byebug to skip next byebug lines until the request (rails server) or until the command (rails console) finishes ? |
Mime content type for gpx not recognized with paperclip gem Posted: 05 May 2016 06:48 AM PDT I have an app in rails 4.26 and ruby 2.3.1 with paperclip 4.3.6, firefox and Ubuntu 14.0.4 64 that i use to upload a gpx file with the code validates_attachment_content_type :gpx, :content_type => { content_type: 'application/xml' also tried with validates_attachment_content_type :gpx, :content_type => { content_type: 'application/gpx+xml' } in my Track model but doesn't pass the validation with a valid gpx file. If I validate by name extension like validates_attachment_file_name :gpx, matches: /gpx\Z/ loads fine. When I run the file command: $ file demofilelite.gpx --mime-type -b I get application/xml as output I tried using a paperclip.rb file in config/initializers with Paperclip.options[:content_type_mappings] = { gpx: %w(application/xml) } But it didn't work either. How do I make paperclip recognize a gpx file byt mime content? |
Rails testing controller private method with params Posted: 05 May 2016 06:27 AM PDT I have a private method in a controller private def body_builder review_queue = ReviewQueueApplication.where(id: params[:review_queue_id]).first ... ... end I would like to test just the body_builder method, it is a method buidling the payload for an rest client api call. It needs access to the params however. describe ReviewQueueApplicationsController, type: :controller do describe "when calling the post_review action" do it "should have the correct payload setup" do @review_queue_application = ReviewQueueApplication.create!(application_id: 1) params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id }) expect(controller.send(:body_builder)).to eq(nil) end end end If I run the above it will send the body_builder method but then it will break because the params have not been set up correctly as they would be in a call to the action. I could always create a conditional parameter for the body_builder method so that it either takes an argument or it will use the params like this def body_builder(review_queue_id = params[:review_queue_id]) and then in the test controller.send(:body_builder, params) , but I feel that changing the code to make the test pass is wrong it should just test it as it is. How can I get params into the controller before I send the private method to it? |
Need to know weired behavior of angular and rails applicaiton Posted: 05 May 2016 06:32 AM PDT I am working on an application developed in angular on front end and rails on back-end. I have just faced a weired problem. I have a angular url defined in app.js when('scorecard/currentscore', { templateUrl: 'scorecard/card.html', controller: 'ScorecardController' }) And in scorecard/card.html , the previous developer had to use date so he changed filename from scorecard/card.html to scorecard/card.html.erb and used date like <%= Date.current.strftime("%B") %> . It generates no error but it shows weird behavior. Like first time when feature was deployed it was march. So first time the file was accessed on March. So in browser it shows March . So now even if it is May it is still showing March. I just put one space in that file, refreshed browser and it started showing current month. I have verified this issue on multiple systems. Until you made a simple change in the file, it keeps on showing the previously visited date. First time I have tested this in April. It was showing March. I put one space and it started showing April. And when even May started, it keep on showing April. I have again put some space and some text and it showed May. Similarly I have an angular controller. I needed to access a ruby constant defined in constants.rb file. I changed my controller extension and put .erb after .js. So until I change that file, it only shows previously visited value of that constant. That constant is actually a date array which should be automatically updated on each day. Can any body tell me what is this behavior? |
How to do configuration for date [on hold] Posted: 05 May 2016 06:38 AM PDT I had created the table t.date :freeze_attendance_till here i need to be do previous date should be unclickable and feature date can clickable, means if he didn't put an attendance to any employee n the day goes off means in the next only admin can only put the attendance. Application configuration can any one help me out |
Ruby on Rails, Polymorphic User Types Posted: 05 May 2016 06:13 AM PDT I am implementing a Polymorphic relationship between my main User model and User type models: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations . I am using Devise and so want to keep the core user credentials (first_name, email, password etc) separate. I tried STI before this but there was too much redundancy in the user registration fields in Active Admin. I would like to know that I have the right approach here: class AddIdentifiableTypeToUsers < ActiveRecord::Migration def change add_column :users, :identifiable_id, :integer add_column :users, :identifiable_type, :string end add_index :users, :identifiable_id end class User < ActiveRecord::Base belongs_to :identifiable, polymorphic: true end class Guardian < ActiveRecord::Base has_many :users, as: :identifiable end class Student < ActiveRecord::Base has_many :users, as: :identifiable end When I tried register a new user it tells me I need to provide a collection for identifiable. I take it this has to be done manually through the console? How do I do this? And if I put in "student" for example as an option will it know automatically to associate this with the student table in the manner above? EDIT: Or can it be done something like this: User.rb IDENTIFIABLE_TYPE_VALUES = %w{Student Guardian} ? Finally is this a robust and sustainable approach for different user types? Each user has mostly common attributes but there are some differences. Thanks. |
Rails grocer doesn't send push notifications Posted: 05 May 2016 06:32 AM PDT I have this code below: def build_push_notification pusher = Grocer.pusher( certificate: "..", # change path gateway: "gateway.push.apple.com", port: 2195 ) notification = Grocer::Notification.new( device_token: "..", alert: "У вас новый заказ!", badge: 42 ) pusher.push(notification) end In "certificate" and "device_token" i have i valid data. I'm just push a notification to iOS device and this was no errors. pusher.push(notification) returns value and it seems be good. But there are no push notification in iOS device. What i do wrong? May i have troubles with certificate? |
How do we get the number of create/update/rollback records in a ActiveRecord transaction Posted: 05 May 2016 05:47 AM PDT In a ActiveRecord transaction block, how do I get to know the number of records that were created/updated/rollbacked? for specific model. This information is needed to know the history of what happened during the transaction job and report to the user. |
Rails textarea and content_for Posted: 05 May 2016 06:41 AM PDT Is it possible to use one textarea and few content_for . My goal is split content for few parts I want to use like it content_for :header , content_for :body and content_for :footer so i want to write full text and separate it yield :header then some content yield :body then images and yield :footer i dont want to create textarea for each content_for Any suggestions? |
Rails setting selection tag to predifined value Posted: 05 May 2016 05:20 AM PDT I have a add function + view. In some cases a user can specify to do some action and call a function that should submit a id to the add function. (that works) Now I wanted that if this param is not nil then a selection tag should be predifined with this value. I tried this: <% if !params[:channel_id].nil? %> <% :channel_id << params[:channel_id] %> <% end %> Thats not working. selection tag looks like this: <%= f.collection_select :channel_id, @channels, :id, :channelname, {prompt: (t "channel.add.prompt")}, class: "form-control", :required => :true %> is there a solution to achieve this? |
Restriction for post to the map display Posted: 05 May 2016 05:10 AM PDT i'm currently building a web app, and I encounters some problems. I want the map display posts that are pushed (so push == true). For that, i'd try a lot of conditions, but it's never working. I feel I am not far from the goal, but for now, the map no reference points. posts controller : class PostsController < ApplicationController before_action :authenticate_user! before_action :set_post, only: [:show, :edit, :update, :destroy] before_action :owned_post, only: [:edit, :update, :destroy] # GET /posts # GET /posts.json def index @posts = Post.all.order("push_updated_at DESC") if @posts.push == true @hash = Gmaps4rails.build_markers(@posts) do |post, marker| marker.lat post.latitude marker.lng post.longitude end end end # GET /posts/1 # GET /posts/1.json def show end # GET /posts/new def new @post = current_user.posts.build end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = current_user.posts.build(post_params) respond_to do |format| if @post.save @post.update(push: false) format.html { redirect_to @post, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update @post = Post.find(params[:id]) respond_to do |format| if @post.update(post_params) format.html { redirect_to @post, notice: 'Post was successfully updated.' } format.json { render :show, status: :ok, location: @post } else format.html { render :edit } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def post_params params.require(:post).permit(:user_id, :title, :description, :image, :push, :push_updated_at, ingredients_attributes: [:id, :name, :_destroy]) end def owned_post unless current_user == @post.user flash[:alert] = "That post doesn't belong to you!" redirect_to root_path end end end views/posts/index : <div class="title text-center"> <h1>Alors ? On mange quoi ?</h1> </div> <br> <%= render 'map' %> <%= render 'post' %> & views/posts/map : <script src="//maps.google.com/maps/api/js?v=3.18&sensor=false&client=&key=&libraries=geometry&language=&hl=®ion="></script> <script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js"></script> <script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/src/infobox_packed.js' type='text/javascript'></script> <!-- only if you need custom infoboxes --> <div style='width: 800px;'> <div id="map" style='width: 800px; height: 400px;'></div> <script type="text/javascript"> handler = Gmaps.build('Google'); handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){ markers = handler.addMarkers(<%=raw @hash.to_json %>); handler.bounds.extendWith(markers); handler.fitMapToBounds(); }); </script> </div> </div> So if you have any suggestions about that, you're welcome !! |
How to implement a many-to-many in ActiveAdmin? Posted: 05 May 2016 04:55 AM PDT There a many-to-many: class Employee < ActiveRecord::Base has_many :employees_and_positions has_many :employees_positions, through: :employees_and_positions end class EmployeesAndPosition < ActiveRecord::Base belongs_to :employee belongs_to :employees_position end class EmployeesPosition < ActiveRecord::Base has_many :employees_and_positions has_many :employees, through: :employees_and_positions end How to implement a choice (check_boxes) positions in the form when adding an employee? I wrote this variant: f.inputs 'Communications' do f.input :employees_positions, as: :check_boxes end It displays a list of positions in the form, but does not save nothing to the table (employees_and_positions). How to fix? |
I am creating shopify app,and i need to filter the customers from particular customergroup Posted: 05 May 2016 05:20 AM PDT I am using the following API to get Customer group. ShopifyAPI::CustomerGroup. I got customer group names and id but i am not able to retrive the customers for particular customer group.Kindly suggest some ideas. |
Bootstrap 3 not loading Posted: 05 May 2016 05:27 AM PDT I'm trying to use some basic bootstrap on my site but it's just not doing anything. I have installed the 'bootstrap-sass' gem and written the css code in custom.css.sass but there is no any change in the site
This is the custom.css file @import "bootstrap-sprockets"; @import "bootstrap"; /*universal */ html{ overflow-y: scroll; } body { padding-top: 60px; } section{ overflow : auto; } textarea { resize: vertical; } .center{ tent-align : center } .center h1{ margin-bottom : 10px; } /* topography */ h1, h2, h3, h4, h5, h6 { line-height : 1; } h1 { font-size : 3em; letter-spacing : -2px; margin-bottom : 30px; text-align : center; } h2{ font-size : 1.7em; letter-spacing : -1px; margin-bottom : 30px; text-align : center; font-weight : normal; color : #999; } p { font-size : 1.1em; line-height : 1.7em; } /* header */ #logo{ float : left; margin-right : 10px; font-size : 1.7em; color : #fff; tex-transform : uppercase; letter-spacing : -1px; padding-top : 9px; font-weight : bold; line-height : 1; } #logo:hover { color : #fff; text-decoration : none; } This is the application.html file <!DOCTYPE html> <html> <head> <title><%= full_title(yield(:title)) %></title> <%= stylesheet_link_tag 'default', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'default', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"> </script> <![endif]--> </head> <body> <header class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <%= link_to "samples app", '#', id: "logo" %> <nav> <ul class="nav pull-right"> <li><%= link_to "Home", '#' %></li> <li><%= link_to "Help", '#' %></li> <li><%= link_to "Sign in", '#' %></li> </ul> </nav> </div> </div> </header> <div class="container"> <%= yield %> </div> </body> </html> and this is the home.html file <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <h2> This is the home page for the <a href="http://railstutorial.org/">Ruby on Rails Tutorial</a> sample application. </h2> <%= link_to "Sign up now!", '#', class: "btn btn-large btn-primary" %> </div> <%= link_to image_tag("rails.png", alt: "Rails"), 'http://rubyonrails.org/' %> Output In application.html I've chanaged the (stylesheet_link_tag 'application' to stylesheet_link_tag 'default' ) and (javascript_include_tag 'application' to javascript_include_tag 'default' ) as it was sending an error as no method error |
Before_action method "Filter chain halted as :route rendered or redirected" . in Application Controller Rails Posted: 05 May 2016 06:01 AM PDT In a before_action , I am checking if a user is logged in. If the user is already logged in then I check their role and redirect them to specific url according to their role. But i have an issue that states: Filter chain halted as :route rendered or redirected My code is def route if user_signed_in? redirect_to '/admin/admins/dashboard' if current_user.admin? redirect_to '/parent/parents/dashboard' if current_user.parent? redirect_to '/mosque/mosques/dashboard' if current_user.mosque? else redirect_to '/users/sign_in' end end Please help me I am stuck since last day. |
I need to choose the size of pizzas and also one count Posted: 05 May 2016 04:37 AM PDT I need help on hum Project. Add your functionality need to choose size and quantity of pizzas. I did the base code with any agile web development with rails Book 4 but with some modifications . The Running Project can be viewed here: http://aqueous-inlet-96557.herokuapp.com/ Please use hum mobile device paragraph open , STILL I did not like views for PCs. The Project Code is here https://github.com/PetersonFonseca/7b I am using this project as Weeks study , however I'm tangled up in this seethe days. All help is welcome Well . Thank you very much . |
Sass undefined variable HEROKU Rails Application Posted: 05 May 2016 05:02 AM PDT I am using Rails 4.2.1 the problem is when I run in heroku I get the error : Sass::SyntaxError: undefined variable: "$text2-font". I have fonts in /app/assets/font.css. The fonts.css @import url('https://fonts.googleapis.com/css?family=Crafty+Girls'); @import url('https://fonts.googleapis.com/css?family=Raleway:400,500,700,300'); @import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700,300'); The application.css @import 'fonts.css'; @import 'font-awesome.css'; @import 'project.css'; The project.css.css @import 'fonts.css'; $default-font: Raleway; $text2-font: 'Open Sans'; $text-default-font: ff2; $price-font: ff4; $members-font: ff5; $idea-font: ff6; .tm { font-family: $text2-font; font-size: 0.9em; } … Production.rb Rails.application.configure do config.cache_classes = true config.eager_load = true config.consider_all_requests_local = false config.action_controller.perform_caching = true config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? config.assets.js_compressor = :uglifier config.assets.digest = true config.log_level = :debug config.i18n.fallbacks = true config.active_support.deprecation = :notify config.log_formatter = ::Logger::Formatter.new config.active_record.dump_schema_after_migration = false config.assets.css_compressor = :sass config.assets.compile = true config.assets.precompile << /\.(?:svg|eot|woff|ttf)$/ end If I run the application locally I have no problem, but if I run in heroku I am getting the error that I mentioned before. |
Rails association user & contacts throwing error Posted: 05 May 2016 04:07 AM PDT Amended the code base in 'contacts controller' from @contacts = Contact.all to @contacts = current_user.contact so a user can see only their contacts (currently any user sees all the contacts) This is throwing the below error. Tried tweaking but still no success and have checked the database in psql and both have id column. Any ideas or amendment needed in the code? Failure/Error: <% if @contacts.any? %> ActionView::Template::Error: PG::UndefinedColumn: ERROR: column contacts.user_id does not exist LINE 1: SELECT 1 AS one FROM "contacts" WHERE "contacts"."user_id" ... ^ : SELECT 1 AS one FROM "contacts" WHERE "contacts"."user_id" = $1 LIMIT 1 Contacts Controller class ContactsController < ApplicationController before_action :contact, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! def index @contacts = current_user.contact end def new @contact = Contact.new end def create Contact.create(contact_params) redirect_to '/contacts' end def show end def edit end def update @contact.update(contact_params) redirect_to '/contacts/' + "#{@contact[:id]}" end def destroy @contact.destroy redirect_to '/contacts' end private def contact_params params.require(:contact).permit(:firstname, :surname, :email, :phone, :image) end def contact @contact = Contact.find(params[:id]) end end User controller class UsersController < ApplicationController end Contact model class Contact < ActiveRecord::Base belongs_to :user has_attached_file :image, styles: {thumb: "100x100>"} validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ end User model class User < ActiveRecord::Base has_many :contacts, dependent: :destroy devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end Index html <%if user_signed_in? %> <%= link_to 'Log out', destroy_user_session_path, method: :delete %> <%end%> <% if @contacts.any? %> <% @contacts.each do |contact| %> <%= link_to image_tag(contact.image.url(:thumb)), contact_path(contact) %> <h3><%= contact.firstname%> <%=contact.surname%></h3> <%=contact.email%><br /> <%=contact.phone%> <br /> <br /> <%end%> <%else%> No contacts yet! <%end%> <br /> <br /> <%= link_to 'Add a contact', new_contact_path%> Schema ActiveRecord::Schema.define(version: 20160504125849) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "contacts", force: :cascade do |t| t.string "firstname" t.string "surname" t.string "email" t.integer "phone" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree end |
capybara feature spec hover+click Posted: 05 May 2016 03:33 AM PDT I'm using rspec + capybara + poltergeist. When I try to simulate hover then click on an element I get an error. Problem should be with using them together since when I delete the click from behind the hover it doesn't throw any error. How can I make this work? scenario "successfully", js: true do sign_in(user) visit root_path within "#postcomment-#{post_comment.id}" do page.find(".post-comment-body").hover.find("#activate-comment-edit-#{post_comment.id}").click end .... error: 1) updating post successfully Failure/Error: page.find(".post-comment-body").hover.find("#activate-comment-edit-#{post_comment.id}").click NoMethodError: undefined method `click' for #<Enumerator:0x007fe255dd4b10> |
How to name route link? Posted: 05 May 2016 03:26 AM PDT I have a problem with adding name to route link. Below there is screen of routing: I want to name last link: GET /backend/people/:id/vacations/new(.:format) What I tried: resources :vacations, only: [:new, :create] do collection do get 'new', as: 'people_vacation' end end Unfortunately this code duplicates new action. How to avoid this duplication and have only one link(with name) to new action? |
How to apply transaction logic to non database actions in Rails? Posted: 05 May 2016 04:27 AM PDT I have a form in a view that has an input box. If you fill in the input box and press "Save", a system command is executed and the value is persisted to the database. I check If the command has executed successfully and then, If the value has been updated to the database. What I don't do is to run them both in some kind of a "transaction" so the change is complete If both the "system_command == true" and the .update == true . Probably the nested conditionals is a wrong thing to do because If the .update fails, the system command has been executed already and cannot be reversed. def update if system_command # Checks If command was executed successfully respond_to do |format| if @system_command.update(system_command_params) format.html { redirect_to system_commands_path, notice: 'Success' } else format.html { render :index } end end else redirect_to system_commands_path, notice: 'Failed' end end system_command is a method that executes a system command. How could I be 100% sure about the integrity of this method's actions ? |
Rails parameter from controller can not shown in view Posted: 05 May 2016 04:02 AM PDT I'm using ajax to get user selected date from datepicker, then pass them to controller to calculate the result, then pass the result back to view. In my model I have: def mobile_type_count(name,name1,field, filed1,value, start_time, end_time ) ........ end Controller analyzer_controller.rb def data start_time = params[:start_date]? Date.parse(params[:start_date]) :Date.iso8601 end_time = params[:end_date]? Date.parse(params[:end_date]) :Date.iso8601 @iphone =Analyzer.new. mobile_type_count('deviceOS','mobileNum','$deviceOS', '$mobileNum','iOS' , start_time , end_time ) @android = Analyzer.new. mobile_type_count('deviceOS','mobileNum','$deviceOS', '$mobileNum','Android' , start_time, end_time ) end View data.html.erb <div class="input-daterange input-group" id="datepicker"> <input type="text" class="input-sm form-control" name="start" value="2016-04-11" id="startDate" /> <span class="input-group-addon">to</span> <input type="text" class="input-sm form-control" name="end" value="2016-04-13" id="endDate" /> </div> <%= button_tag(type: 'submit', class: "btn btn-default btn-sm", :id => 'get_data' ) do %> Submit <% end %> </div> <div class="ibox-content"> <%= pie_chart({"iphone" => @iphone, "android" => @android}) %> </div> Ajax <script type="text/javascript"> $(document).ready(function() { $('#get_data').click(function(){ var sd = $('#startDate').val(), ed = $('
|
No comments:
Post a Comment