Rails creating duplicates when editing nested form Posted: 25 Jan 2017 07:31 AM PST I did a lot of googling, and all come back to adding :id to the permitted attributes, but that doesn't work in my case so: How can i prevent multiple empty rows (in related tables)from being created when editing a nested form? Every time i eddit a form, it doubles the amount of empty related records. The controller: class EnquiriesController < ApplicationController before_action :authenticate_user! load_and_authorize_resource # before_action :set_enquiry, only: [:show, :edit, :update, :destroy] #11-1-2017 Devise geinstalleerd, nog verder afmaken!(oa onderstaande uncommenten) # GET /enquiries # GET /enquiries.json def index # @enquiries = Enquiry.all @enquirie = current_user.enquiries end # GET /enquiries/1 # GET /enquiries/1.json def show end # GET /enquiries/new def new @enquiry = Enquiry.new @enquiry.enquirymeasures.build #@enquiry.measurements.build @enquiry.tools.build @enquiry.build_applicant @enquiry.signatures.build @enquiry.gasmeters.build #@enquiry.enquirymeasures.build.build_measurement end # GET /enquiries/1/edit def edit #nog op kunnen slaan!!!! 1-01-17 Marco @enquiry = Enquiry.find(params[:id]) @enquiry.enquirymeasures.build @enquiry.tools.build @enquiry.build_applicant @enquiry.signatures.build @enquiry.gasmeters.build end # POST /enquiries # POST /enquiries.json def create @enquiry.user_id = current_user.id @enquiry = Enquiry.new(enquiry_params) #@enquiry.enquirymeasures.build respond_to do |format| if @enquiry.save format.html { redirect_to @enquiry, notice: 'Enquiry was successfully created.' } format.json { render :show, status: :created, location: @enquiry } else format.html { render :new } format.json { render json: @enquiry.errors, status: :unprocessable_entity } end end end #approved_enquiry_notification # PATCH/PUT /enquiries/1 # PATCH/PUT /enquiries/1.json def update @enquiry = Enquiry.find(params[:id]) respond_to do |format| if @enquiry.update(enquiry_params) format.html { redirect_to @enquiry, notice: 'Enquiry was successfully updated.' } format.json { render :show, status: :ok, location: @enquiry } else format.html { render :edit } format.json { render json: @enquiry.errors, status: :unprocessable_entity } end end end # DELETE /enquiries/1 # DELETE /enquiries/1.json def destroy @enquiry.destroy respond_to do |format| format.html { redirect_to enquiries_url, notice: 'Enquiry was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_enquiry @enquiry = Enquiry.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. #25-1 MG alle attributes hadden ook :id def enquiry_params params.require(:enquiry).permit(:id, :reference, :location, :description, :date, :amount, :approved, enquirymeasures_attributes: [:id, :responsible, :done, :needed, :measurement_id, :user], tools_attributes: [:id, :handtool, :other, :motorvehicle, :compressor, :ramp, :scaffold, :crane, :ladder, :generator, :tankladder], applicant_attributes: [:id, :name, :email, :contractor_id], signatures_attributes: [:id, :date, :signature, :representative_id], gasmeters_attributes: [:id, :date, :tester, :signature, :oxigen, :o_needed, :o_continu, :explosives, :e_needed, :e_continu, :mat1, :mat1_needed, :mat1_continu, :mat2, :mat2_needed, :mat2_continu, :mat3, :mat3_needed, :mat3_continu], controls_attributes: [:id, :enquirycheck, :workspacecheck, :enquiry_id]).merge(user_id: current_user.id) end end The models: main: class Enquiry < ActiveRecord::Base has_many :enquirymeasures, dependent: :destroy accepts_nested_attributes_for :enquirymeasures, :reject_if => lambda { |a| a[:responsible].blank? }, :allow_destroy => true has_many :tools, dependent: :destroy accepts_nested_attributes_for :tools has_many :controls, dependent: :destroy accepts_nested_attributes_for :controls has_one :applicant, dependent: :destroy accepts_nested_attributes_for :applicant has_one :contractor, through: :applicant has_many :signatures, dependent: :destroy accepts_nested_attributes_for :signatures has_many :representatives , through: :signatures, :source => :representatives has_many :gasmeters, dependent: :destroy accepts_nested_attributes_for :gasmeters belongs_to :user #voor de goedkeuring mail after_create :send_confirmation_mail def send_confirmation_mail ModelMailer.new_enquiry_mail(self).deliver end #after_update :send_approved_mail #def send_approved_mail # if params[:approved] == '1' # if :approved == '1' # ModelMailer.enquiry_approved_mailer(self).deliver # end
Rails 4 + Simpleform + datetimepicker-rails How do I add a default time of 6:45pm Posted: 24 Jan 2017 08:22 AM PST Want to have a default time of 645pm in a form. I am using Rails 4 , Simple form & datepicker bootstrap gem. = f.input :started_at, as: :string, class: 'form-control', input_html: { value: l(@happening.started_at, format: :date_time_picker), class: 'date_time_picker' }, label: "Start at" I have tried a number of things including using default: '645' after the date_time_picker and reading the Simpleform documentation | How to delete a collection matching a condition Posted: 24 Jan 2017 08:19 AM PST I would like to delete all posts associated to every user of my application matching a determined condition. In particular I would like to delete all posts older than 30 days only if a user has more than 20 posts. At first I wrote the following code: users = User.all users.each do |user| if user.posts.any? && user.posts.count > 20 user.posts.delete_all('created_at < ?', 30.days.ago) end end However, looking at the API documentation, method delete_all for collections does not imply the records are actually removed from the database, and that depends precisely on the specified parameter, :nullify or :delete_all Therefore, considering that method delete_all for collections requires one of the above parameters, would the following code be correct: users = User.all users.each do |user| if user.posts.any? && user.posts.count > 20 user.posts.where('created_at < ?', 30.days.ago).delete_all(:delete_all) end end or am I expected to use something different? | React on Rails - ! [remote rejected] master -> master (pre-receive hook declined) Posted: 24 Jan 2017 08:18 AM PST I'm working in rails 4.2.5, recently I have added react_on_rails in my app. I am getting an error when I try to push to heroku. git push heroku master Counting objects: 963, done. Delta compression using up to 4 threads. Compressing objects: 100% (793/793), done. Writing objects: 100% (963/963), 982.20 KiB | 0 bytes/s, done. Total 963 (delta 384), reused 160 (delta 70) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Deleting 18 files matching .slugignore patterns. remote: -----> Node.js app detected remote: mkdir: cannot create directory '/tmp/build_2116c2c5be27b9852c9d716798b3bcf9/.heroku': Not a directory remote: ! Push rejected, failed to compile Node.js app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to acceptance. remote: To https://git.heroku.com/acceptance.git ! [remote rejected] master -> master (pre-receive hook declined) Any help is much appreciated. | Rescuable after_commit callbacks (Rails 3) Posted: 24 Jan 2017 08:06 AM PST I have a model with several after_commit callbacks. In case any of the callbacks raises an exception, all others will be skipped. I want to ensure that all callbacks are ran (even if one fails), without explicitly wrapping each of them with begin & rescue . Is there a way to so? I've looked into rescuable option of CallbackChain but it doesn't seem to be stuiable for this case class Order < ActiveRecord::Base after_commit :a, :b def a() 'in a' end def b() puts 'in b'; fail 'Bad callback' end end In this case, callback a will not run: >> Order.create! in b [ERROR] Bad callback | best practice : should i create a new controller or not ? in order to respect a good architecture Posted: 24 Jan 2017 08:20 AM PST I'm working on an application where both notifications and history are needed, and what makes it quite difficult is the fact that there is the notion of 'context'. For example when the user is in a certain view, he must see only the notifications and the histories related to that context. There is a controller for each, but when I want to update the notifications in the client side ( live update using the Pusher ), from the server side I need to know the context where the user is. The solution put in place is to send an ajax request from the client side specifying the context he is in, with the route of course. Now the question is, in order to respect a good architecture, since the ajax request sends the context which is used for both notification and history, should I create a controller to deal with that ( and then that controller will contact both controllers ) or should I use one of them?. Thanks | Ruby on Rails function for model attribute Posted: 24 Jan 2017 08:09 AM PST I have one active record model called Task with following attributes: name (string) due (date) priority (int) How do I create a function for priority so I can call it something like this @task.priority.to_str would produce "Low", "High" based off the integer value I don't want to override the attribute method to print out the string because I need to access the actual value. | How do you get a list from complex active record has_many involved from a subset of downstream objects Posted: 24 Jan 2017 08:17 AM PST I'm having a hard time getting a list of the leagues involved from a subset of games. class League has_many :teams has_many :games, :through => :teams end class Team belongs_to :league has_many :home_games, :foreign_key => team_a_id, :source => :game has_many :away_games, :foreign_key => team_b_id, :source => :game end class Game belongs_to :home_team, :class_name => Team belongs_to :away_team, :class_name => Team end Data Examples: AFC - PATRIOTS - Home Away G1(PATRIOTS vs DALLAS) G2(PATRIOTS vs PITTSBURG) PITTSBURG - G2(PATRIOTS vs PITTSBURG) NFC - DALLAS - G1(PATRIOTS vs DALLAS) G3(DALLAS vs GREENBAY) G4(DALLAS vs SEATTLE) GREENBAY G3(DALLAS vs GREENBAY) SEATTLE G4(DALLAS vs SEATTLE) Given a subset/collection of Game objects[G1,G4], is there a way to return the Leagues associated? (Return AFC & NFC) Find all Games that have NFC teams [G1,G3,G4] The challenge Im having with is the home_team / away_team seperation thanks | How does one integrate Duo Mobile with Devise and Rails? Posted: 24 Jan 2017 07:55 AM PST The documentation for Duo's supported Ruby library is sparse. This question understandably mentions overriding Devise's session controller, but how? There does not seem to be a source for a clear explanation of how to integrate Duo with Devise. There is this gem, but it doesn't seem to be very active and I couldn't get it working. How do I do this? | Devise 401 Unauthorized Posted: 24 Jan 2017 07:43 AM PST I'm using Ruby 4.2.3 and Devise 4.2.0 and I'm trying to sign in using POST method ($resource AngularJS) but 'I'm getting 401 Enauthorized error ('You need to sign in or sign up before continuing') I'm following this Documentation which is working fine if I try outside my app. For instance using 'Postman'. Alright, some code: My angular controller to send the log in data to server: $scope.log_in = function(){ sendData = new Sign_in($scope.user); sendData.$save(null, function(response){ $cookies.put("user_email", $scope.user.email); $cookies.put("user_token", response.data.authentication_token); }, function(error){ console.log('error log in'); }); } my session devise controller (as exactly as the tutorial) class Users::SessionsController < Devise::SessionsController def create user = warden.authenticate!(auth_options) token = Tiddle.create_and_return_token(user, request) render json: { authentication_token: token } end def destroy Tiddle.expire_token(current_user, request) if current_user super #render json: {} end private # this is invoked before destroy and we have to override it def verify_signed_out_user end end my postman example that shows that is working: What am i missing? I try to look out all around but I couldn't find any updated info. Any guide you could recommend? Thanks! | undefined method `permit' for "<p>tinymce</p>":String Posted: 24 Jan 2017 07:56 AM PST Im trying to implement tinyme gem and I get this error: undefined method `permit` for "<p>tiny mce</p>":String This is the controller: def note_params params.require(:note).permit(:contact_id, :note) end The View: <%= simple_form_for(@note) do |f| %> <%= f.error_notification %> <div class="form-group hidden-xs-up"> <label><i class="fa fa-address-book-o" aria-hidden="true"></i> Contact</label> <%= f.select :contact_id, get_contact.collect{@contact.id},{}, class:"form-control" %> </div> <div class="form-group over-hide"> <label><i class="fa fa-file-text-o" aria-hidden="true"></i> Note</label> <%= text_area_tag :note, "", :class => "form-control tinymce", :rows => 10, :cols => 60 %> <%= f.button :submit, class: "btn btn-info mt-2 float-sm-right" %> </div> <% end %> How should I fix this issue ? | Add autocomplete feature to rails app with selectize.js Posted: 24 Jan 2017 07:34 AM PST It's been two days that I'm fighting on a "simple" task. Adding an autocomplete field in a form on my rails application. I'm running ruby 2.3.3 and rails 5.0.1. So far I've tried a bunch of different options such as: - Elasticsearch - Rails-jquery-autocomplete Now I'm giving a go to selectize.js. I added the gem to my gemfile: gem "selectize-rails" And I have included it in my application.js //= require jquery //= require jquery_ujs //= require selectize //= require turbolinks //= require bootstrap-sprockets //= require_tree . //= require main I have created an action in my controller that returns the data from a table called Interests in a json format: def users_interests_search @interests = Interest.all respond_to do |format| format.js {} format.json {render json: @interests} end end And in my script, I'm using the following (taken from here using the rottenTomato example): $('.test-selectize').selectize({ valueField: 'title', labelField: 'title', searchField: 'title', options: [], create: false, render: { option: function(item, escape) { return '<div>' + '<span class="title">' + '<span class="ciccioname">' + item.name + '</span>' + '</span>' + '</div>'; } }, load: function(query, callback) { if (!query.length) return callback(); $.ajax({ url: '/users-interests-search', type: 'GET', dataType: 'json', success: function(res) { console.log(res); console.log(res[0].name) $('selectize-dropdown-content').append('<span class="ciccioname">' + res[0].name + '</span>') } }); } }); Although I do see the AJAX call made and the JSON returned, not much is going on on the actual page. Any suggestion on the matter is the very welcome (or any other sort of help to get an autocomplete system up and running for that matter :) ). Cheers! Andrea Update: Here is the console output after changing the ajax call (see above) Console screenshot | Rails: Serialization of custom class for flash messages Posted: 24 Jan 2017 07:06 AM PST I can't seem to figure out how flash messages in RoR insist on being serialized for the next page view. When setting a simple type to e.g. flash[:notice], all is well to get it across to the next page view. When I however try and set the value of flash[:notice] to a custom class, it serializes only the properties: flash[:notice] = Info.notice("Content...", "Title") ... equates to ... {"type"=>"notice", "content"=>"Content...", "title"=>"Title"} ... which has no knowledge of the class it serialized. One solution I found was to use .to_yaml before doing a redirect, and then use YAML.load at the later step, but I don't find that viable. So my question is, how would I be able to make sure that it automatically serialize this object, to properly be deserialized at a later stage? Rails: 4.2.5.1, Ruby: 2.2.4p230 Thanks | Rails + Devise ActionController::InvalidAuthenticityToken Posted: 24 Jan 2017 07:03 AM PST Cheers! I use Devise gem for authenticating users and locally (development env) I always get this ActionController::InvalidAuthenticityToken exception on devise::session/create action, no big deal I thought and added some dirt: class ApplicationController < ActionController::Base include EmailConcern # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :authenticate_user! def handle_unverified_request true end ... end All right, no more authenticity_token exceptions, I don't mind if it happens only in dev env. But! There is another problem - :authenticate_user! is never worked, so current_user is always nil and I always getting redirected with 401 unauthorized to new session path again. User's credentials are valid and user exists in the DB. router.rb Rails.application.routes.draw do resources :coupons devise_for :users, path: 'u' What could be the origin of this issue? ruby-2.2.2@rails-4.2.0 | Rails: load different modules for each environemnt Posted: 24 Jan 2017 06:52 AM PST I have rails application with two environments. Each environment has its own schema. How can configure rails to load specific modules for each environment? e.g modules app/models/a.rb app/models/b.rb when running with environment X and app/models/c.rb app/models/d.rb when running with environment Y. | Sprockets::FileNotFound with jquery-ui-bootstrap Posted: 24 Jan 2017 07:09 AM PST Strange issue. Following the gem's docs I seem to be running into the error, Sprockets::FileNotFound in PostIndex: couldn't find file 'ui-bootstrap/jquery-ui-bootstrap' with type 'text/css' Here is how I have my files setup: Gemfile gem 'jquery-rails' gem 'twitter-bootstrap-rails' gem 'jquery-ui-rails' gem 'jquery-ui-bootstrap-rails' application.css *= require_tree . *= require ui-bootstrap/jquery-ui-bootstrap *= require jquery-ui *= require_self application.js //= require jquery //= require jquery_ujs //= require jquery-ui //= require twitter/bootstrap //= require turbolinks //= require_tree . I'm using the latest versions of all of these gems. | Sunspot Solr fulltext search Posted: 24 Jan 2017 06:17 AM PST I'm having some trouble getting the right results in when searching my Issue model with Sunspot Solr. Initially, I was doing a fuzzy search using ~ (tilde) but this is causing tons of unrelated items to show up. I need to be able to search the problem and effected_versions fields in my DB: In my Issue model: class Issue < ActiveRecord::Base searchable do string :type text :problem, :effected_versions end end And my initial search string was: Issue.search { with :type, :cve; fulltext product.gsub(/\s|$/, "~ ") + version }.results This worked relatively fine, however any result that might have been 'close' to what the person was looking for was being returned. So, if the person searches for linux firmware:1 they were getting unrelated results along with related ones. Basically, anything that has the word "Linux" and "firmware:1" are being returned although in most cases they aren't related. So, I've decided I need to do away with fuzzy search and get more specific. If someone searches I need only those specific results to return, based on what's in the product and effected_versions columns in my DB. I was thinking about doing an exact phrase search, but I can't interpolate the variables that are being passed when doing this because of the double-quoting requirement. It just returns the literal string: Issue.search{with :type, :cve; fulltext '"#{product} #{version}"'}.results D, [2017-01-24T08:58:59.738474 #18849] DEBUG -- : SOLR Request (4.1ms) [ path=select parameters={fq: ["type:Issue", "type_s:cve"], q: ""#{product} #{version}"", fl: "* score", qf: "problem_text effected_versions_text", defType: "edismax", start: 0, rows: 30} ] => [] Is there a way around this so I can minimize incorrect results from showing? Update I found a way around the double-quoting requirement by wrapping my dynamic content in %{} , but now that's too restrictive. Is there a happy medium? | Issue regarding cursor styling for a disabled button by javascript Posted: 24 Jan 2017 06:45 AM PST In my ruby on rails application I am using some javascript on one of my view page to make a submit button with id "submitorder" disabled. And I have done this successfully using the following line of code. $('#submitorder').prop('disabled', true); It is working fine. But now I want to make the cursor as 'not-allowed' also when hovering on that submit button. That's why I have used the following lines of code to make the submit button disabled and as well as to make the cursor as 'not-allowed' $('#submitorder').prop('disabled', true); $('#submitorder').css( 'cursor', 'not-allowed' ); But unfortunately the button becomes disabled only. There is no change in the cursor styling. Please tell me why this is happening and give me clues to figure out this. Thanks in advance!! | Mouse over to display more information using jquery with rails model Posted: 24 Jan 2017 05:37 AM PST I have 5 rows of 10 buttons arranged in a table. This represents a vending machine where there are 5 rows of 10 slots each. Each button displays basic information such as quantity of the items left in that slot. This is already done. I want to allow mouse over the buttons to pop up a bigger window to show more information about each of the slot.These information must be retrieved from the vending machine model. It is not like popover where I just enter some static text. Here I have to query the db to display actual data. html.erb <% for i in item do %> <% if !VendingMachine1.where(:slotID => i).first.nil? %> <% vm = VendingMachine1.where(:slotID => i).first %> <%= link_to vending_machine1_path(vm.id),:class=>"vmButton",:method => :get do %> <div class="myPara"><%= i %> </div> <div class="myPara">Q:<%= find_vm_quantity(vm) %> </div> <div class="myPara">P:<%= vm.priority %></div> <div class="myPara"><%= vm.identifier %></div> <% end %> <% else %> <div class="vmButton"> <div class="myPara"><%= i %> </div> <div class="myPara">Q:-</div> <div class="myPara">P:-</div> <div class="myPara">-</div> </div> <% end %> <% end %> any suggestions on how I could achieve that? thank you. | Ruby Object mutations within sidekiq workers Posted: 24 Jan 2017 07:41 AM PST I have a wrapper that sends user updates to an external service, on a regular basis, running inside a Sidekiq worker. Each User has its own Sidekiq Job. Sidekiq is setup to use 20 threads. It's a Rails 5.0.1 app, MRI Ruby 2.3.0. Webserver is Passenger 5 Community. If I over simplify, the code looks like this: class ProviderUserUpdateJob < ApplicationJob queue_as :default def perform(user_id) user = User.find(user_id) Provider::User.new(user).push_update end end class Provider::User def initialize(user) @user = user end def push_update SomeApiWrapper.call( user_id: @user.id, status: @user.status ) end .... end Now, the BIG problem that I only have on production and I finally catched up by looking at the logs can be summarized like this : class Provider::User def initialize(user) @user = user end def push_update SomeApiWrapper.call( user_id: @user.id, # Some user status: @user.status # NOT THE SAME USER !!! (and I have no idea where he is coming from) ) end .... end 2 Questions: How it this even possible? Does it comes from Provider::User being by essence a globally accessible object, so, from threads to threads, everything gets mixed up in a mutating soup?! If I only use "functional" style, without any instance, passing parameters and outputs from static methods to static methods, can it solve my problem or am I completely wrong? How can I fix this? Ultimately, is there any way to really battle test this kind of code so I can be sure not to mix users data? | truncate and restart identity of a set of tables Posted: 24 Jan 2017 05:44 AM PST My application uses Postgresql . I would need to remove all rows from a set of tables (table1 to table4 ) and restart the id with one command from a rb file. In the Postgresql documentation I found that TRUNCATE with RESTART IDENTITY would do the job as follows: TRUNCATE table1, table2, table3, table4 RESTART IDENTITY; According to How to restart id counting on a table in PostgreSQL after deleting some previous data? at Stackoverflow, I can use the following command: ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY") So putting together the two documentations, would it be correct to use the following command: ActiveRecord::Base.connection.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY") considering that in the API dock documentation the connection method is reported as deprecated or moved?. | how to display one controller show action in another controller action in rails Posted: 24 Jan 2017 05:17 AM PST I am using two controller incident and incident_list, i am displaying all incidents in incident_list/index page when click on show button in each incident i want to display that incident details IncidentListController def show @incidents = Incident.all @incident = Incident.find(params[:id]) render "incidents/show" end IncidentController def show @incidents = Incident.all @incident = Incident.find(params[:id]) end incidnet_lists/index.html.erb <table> <table class="table table-striped table-bordered"> <thead > <tr> <th class="c2">Case ID</th> <th class="c2">Call Type</th> <th class="c2">Number of People</th> <th class="c2"></th> </tr> </thead> <tbody> <tr> <td><%= inc.id %> </td> <td><%= inc.call_type %> </td> <td><%= inc.no_of_people %></td> <td><%= link_to 'Show', @incidents %></td> </tr> </tbody> </table> incidents/show.html.erb <table class="table table-striped table-bordered"> <thead> <tr> <td class= "c2" > Case Id </td> <td class= "c2"> Caller Name </td> <td class="c2"> Contact Number </td> <td class= "c2"> Calling For </td> <td class="c2"> Call Type </td> <tr> </thead> <tbody> <% @incidents.each do |inc| %> <tr> <td> <%= inc.id %> </td> <td> <%= inc.caller_name %></td> <td> <%= inc.contact_number %></td> <td> <%= inc.for_whom %> </td> <td> <%= inc.call_type %> </td> </tr> <% end %> </tbody> </table> when click on show button in the incident_list page incident show page should be display | Rails: Change Status Onclick Posted: 24 Jan 2017 04:56 AM PST I have the following where I am monitoring a job status. What I would like to do is be able to click each div and have a menu appear where I can change the status. Is this possible? | PDFKit Unknown long argument --root-url Posted: 24 Jan 2017 05:55 AM PST I'am trying to use the :root_url parameter with PDFKit like suggested here https://github.com/pdfkit/pdfkit in Resolving relative URLs and protocols section: PDFKit.new(html, root_url: 'http://example.com/').to_file My code: html = Nokogiri::HTML(open("http://stackoverflow.com")) PDFKit.new(html.to_s, root_url:'http://stackoverflow.com/').to_file(file.path) returns wkhtmltopdf error Unknown long argument --root-url . Does anyone know how can I resolve this? versions: wkhtmltopdf 0.12.4 pdfkit 0.8.2 tested also with wkhtmltopdf 0.12.3 pdfkit 0.8.0 | RSpec before in a helper Posted: 24 Jan 2017 04:38 AM PST Is it possible to do something like this? module MyHelper before (:each) do allow(Class).to receive(:method).and_return(true) end end Then in my tests I could do something like: RSpec.describe 'My cool test' do include MyHelper it 'Tests a Class Method' do expect { Class.method }.to eq true end end EDIT: This produces the following error: undefined method `before' for MyHelper:Module (NoMethodError) Essentially I have a case where many tests do different things, but a common model across off of them reacts on an after_commit which ends up always calling a method which talks to an API. I dont want to GLOBALLY allow Class to receive :method as, sometimes, I need to define it myself for special cases... but I'd like to not have to repeat my allow/receive/and_return and instead wrap it in a common helper... | Have username instead of id then nested route /users/:id/nest_routes to /username/nested_routes Posted: 24 Jan 2017 03:42 AM PST Hello i have heaps of routes such as the following resources :users do resources :shipping_methods, only: [:new, :create, :edit, :update, :destroy] resources :cart_items, only: [:create, :index, :destroy] resources :relationships, only: [:create, :destroy] resources :addresses, only: [:new, :create, :edit, :update, :destroy] end They all produce the following route /users/:id/nested_route For instance an edit shipping method view produces the following /users/1/shipping_methods/11/edit How do i make all these routes produce this: /username/nested_route For example the edit shipping method view above should produce the following: /username/shipping_methods/11/edit | ruby on rails error config_check.rb:87:in `initialize': Posted: 24 Jan 2017 03:43 AM PST I have just installed ruby on rails and can not figure out whats wrong with it whenever I run it gives the following error: # Rails Environment Configuration. The system cannot find the file specified. The system cannot find the file specified. C:/RailsInstaller/scripts/config_check.rb:87:in `initialize': No such file or directory @ rb_sysopen - C:\Users\HP/.ssh/id_rsa.pub (Errno::ENOENT) from C:/RailsInstaller/scripts/config_check.rb:87:in `open' from C:/RailsInstaller/scripts/config_check.rb:87:in `<main>' C:\Sites> | Testing a belongs_to relationship in Rails with rspec Posted: 24 Jan 2017 02:51 AM PST I have a model called Page that has many Paragraphs. This all works but I thought it was about time I had some tests. For reasons, I need a count of all the paragraphs a page has, +1 so I know how to number the next paragraph. I do this with a count_paragraphs method in my model: class Page < ApplicationRecord has_many :paragraphs def count_paragraphs paragraphs.count + 1 end end So far so simple. This works fine in my controller, where I use it to create the next paragraph. @paragraph = @page.paragraphs.create(body: para_params[:body], num: @page.count_paragraphs) As mentioned this all works. But in testing, this does not work: it 'has a paragraph count of 1' do expect(subject.count_paragraphs).to eq 1 end it 'successfully counts paragraphs' do subject.paragraphs.new(body: "hello", num: 1) expect(subject.count_paragraphs).to eq 2 end The first test passes, the second does not. It always returns 1. When I binding.pry the test, each new paragraph shows up if I do subject.paragraphs but if I binding.pry in the model, paragraphs just comes back [] . So I am misunderstanding something about the model relationship. Does anyone have any idea what I'm doing wrong here? | Rails bootstrap color depending on value Posted: 24 Jan 2017 05:03 AM PST Project.status can be [1,2,3] . Is there a better way of defining the following logic (color depends on status ), than doing it in the view? - if project.status == '1' %td.bg-success= project.status - elsif project.status == '2' %td.bg-warning= project.status - else %td.bg-danger= project.status | Double has_many attributes Posted: 24 Jan 2017 07:49 AM PST I'm beginner in rails and having trouble finding a proper way out with my problem. I have three models : Conversation, participant, messages which have the following attributes : Conversation : module Messenger class Conversation <ActiveRecord::Base has_many :participants, :class_name => 'Messenger::Participant' def messages self.participants.messages.order(:created_at) end end end Participant : module Messenger class Participant <ActiveRecord::Base has_many :messages, :class_name => 'Messenger::Message' belongs_to :conversation, :class_name => 'Messenger::Conversation' end end Message : module Messenger class Message <ActiveRecord::Base default_scope {order(:created_at)} default_scope {where(deleted: false)} belongs_to :participant, :class_name => 'Messenger::Participant' end end My trouble is that I'm trying to make a single form to create a conversation with a first message in it. The form looks like this : = form_for @conversation, url: messenger.conversations_create_path do |f| .row .col-md-12.no-padding .whitebg.padding15 .form-group.user-info-block.required = f.label :title, t('trad'), class: 'control-label' = f.text_field :title, class: 'form-control' .form-group.user-info-block.required = f.label :model, t('trad'), class: 'control-label' = f.text_field :model, class: 'form-control' .form-group.user-info-block.required = f.label :model_id, t('trad'), class: 'control-label' = f.text_field :model_id, class: 'form-control' = fields_for @message, @conversation.participants.message do |m| = m.label :content, t('trad'), class: 'control-label' = m.text_area :content, class:'form-control' .user-info-block.action-buttons = f.submit t('trad'), :class => 'btn btn-primary pull-right' I've tried many ways to make this form simple but I've encountered some problems which I don't know how to fix using rails properly. I've tried using Field_for to include a message in my conversation form, but since I have nothing saved in my database yet it seems I can't link a message to an unexisting participant. So basically I want my first form, once validated, to create a conversation, link the current user to that conversation and link the message to that first user, but I assume there are ways to do it with the framework and I would not like to do it manually. What is the proper way to follow to achieve that? Am I even on the good track or shoould I change something or add something? Edit : to make it more understandable, a participant got a user_id and a conversation_id, which means this is a relation table. I can't adapt the attributes of my models to make it easier since I must keep it in that way for security reasons. | Extract Data from Excel Spreadsheet into Database in Ruby Posted: 24 Jan 2017 02:47 AM PST I'm looking to extract quite a lot of data from spreadsheets for a Rails application, but I'm doing the extraction through the Rails Console. I have a table called instititutes in my database which currently has around 170 records. I've found far better data in a spreadsheet with c.1000 records and want to import that to my database, but to skip any records that match already. I thought that using the find_or_create_by method would be the best move for this. The spreadsheet has UKPRN and NAME as headers, and the table has ukprn and name as respective columns (as well as others). Using the Roo gem, I've got this so far: require 'roo' xlsx = Roo::Spreadsheet.open(File.expand_path('../Downloads/UKPRN.xlsx')) xlsx.default_sheet = xlsx.sheets.last header = xlsx.row(1) xlsx.each_row do |row| row = Institute.find_or_create_by(UKPRN: ukprn , NAME: name) end This is giving the error NameError: unitialized constant UKPRN . I'm still getting my head back into Ruby so any help would be appreciated. I'm using Ruby 2.2.3 and Rails 5.0.1 Edit: p row shows: ["UKPRN", "NAME"] [10000291, "Anglia Ruskin University"] [10000385, "The Arts University Bournemouth"] [10000571, "Bath Spa University"] [10000712, "University College Birmingham"] [10000824, "Bournemouth University"] [10000886, "The University of Brighton"] [10000961, "Brunel University London"] ...etc |
nokogiri wont parse the file using SAX handler Posted: 23 Jan 2017 07:41 AM PST I have xml file with header <?xml version="1.0" encoding="utf-16"?> and also it contains the <transmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> when used the SAX parser it wont parse. But when manually removed the encoding part and the attributes after transmission;XML parsing success. Being the file is large;I cant use only SAX.Is there any other way to parse this xml file without manually removing the encoding and transmission attributes. | Ruby Minitest: Access variables in setup-method Posted: 23 Jan 2017 07:35 AM PST How can I access variables that are defined inside the setup method in Minitest? require 'test_helper' class TimestampTest < ActiveSupport::TestCase setup do @ag = AG.create(..., foo = bar(:foobar)) @ap = AP.create(..., foo = bar(:foobar)) @c = C.create(..., foo = bar(:foobar)) end [@ag, @ap, @c].each do |obj| test "test if #{obj.class} has a timestamp" do assert_instance_of(ActiveSupport::TimeWithZone, obj.created_at) end end end If I run this @ag , @ap and @c are all nil . bar(:foobar) on line 5-7 is needed to access fixture-data. | Storing user generated scopes / segmentation of model Posted: 23 Jan 2017 07:26 AM PST I'd love to hear what people think might be the best practice for this. I have users which can manage a list of customers. I want them to be able to segment their customers. For instance a segmentation can be customers who have in the last 5 days purchased an item. Or customers who have not purchased an item at all. Ideally i'll allow the segmentation to follow several conditions such as: Customers who have purchased an item in the last 5 days AND was registered less than 2 days ago. How would you go about setting this up and storing it? I can set columns for each condition, but conditions might have different variations in what scope they use. Furthermore it doesn't work if you want them to be able to set several segments. Another idea is to use serialization, if so any thoughts on how to do this? | Ubuntu development configuration with SSL, Puma, and Rails Posted: 23 Jan 2017 07:26 AM PST Goal: get ssl working in development mode (ssl works fine in production on heroku) My setup: Ubuntu 16.04 Rails 5.0.1 Puma 3.6.2 config/environments/development.rb config.force_ssl = true I tried following along with this puma ssl how-to: https://gist.github.com/tadast/9932075 (I am not sure what github procol is regarding pasting above link content here vs referencing it) if I then use the command line method to run puma puma -b 'ssl://127.0.0.1:3000?key=/home/sean/.ssh/server.key&cert=/home/sean/.ssh/server.crt' I am getting Chrome's 'Not Secure' error when trying to access via the browser after attempting to add certificate to ubuntu. sudo cp server.crt /usr/local/share/ca-certificates/ sudo update-ca-certificates Updating certificates in /etc/ssl/certs... 0 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d... done. Should I should see 1 added here? I also tried copying server.crt to /etc/ssl/certs If I proceed past chrome block I get console error: SSL error, peer: 127.0.0.1, peer cert: , #<Puma::MiniSSL::SSLError: OpenSSL error: error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request - 336027804> Instead of using puma on command line I tried adding to config/initializers/puma.rb bind 'ssl://127.0.0.1:3000?key=/home/sean/.ssh/server.key&cert=/home/sean/.ssh/server.crt' and starting: rails s I do not get any page load but console shows: HTTP parse error, malformed request (): # 2017-01-23 10:04:43 -0500: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#>, "rack.multithread"=>true, "rack.multiprocess"=>false, "rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"puma 3.6.2 Sleepy Sunday Serenity", "GATEWAY_INTERFACE"=>"CGI/1.2"} I also tried downgrading puma to 3.5.2 Where am I going wrong? | Test if a method is called inside a module method Posted: 23 Jan 2017 07:23 AM PST I have the following in my module: module SimilarityMachine ... def answers_similarity(answer_1, answer_2) if answer_1.compilation_error? && answer_2.compilation_error? return compiler_output_similarity(answer_1, answer_2) elsif answer_1.compilation_error? || answer_2.compilation_error? return source_code_similarity(answer_1, answer_2) else content_sim = source_code_similarity(answer_1, answer_2) test_cases_sim = test_cases_output_similarity(answer_1, answer_2) answers_formula(content_sim, test_cases_sim) end end ... end I would like to test these "if conditions", to ensure that the right methods are called (all these methods are from SimilarityMachine module). To do that, I have: describe SimilarityMachine do describe '#answers_similarity' do subject { answers_similarity(answer_1, answer_2) } let(:answer_1) { create(:answer, :invalid_content) } context "when both answers have compilation error" do let(:answer_2) { create(:answer, :invalid_content) } it "calls compiler_output_similarity method" do expect(described_class).to receive(:compiler_output_similarity) subject end end end With both answers created I go to the right if (the first, and I'm sure of that because I tested before). However, my result is: 1) SimilarityMachine#answers_similarity when both answers have compilation error calls compiler_output_similarity method Failure/Error: expect(described_class).to receive(:compiler_output_similarity) (SimilarityMachine).compiler_output_similarity(*(any args)) expected: 1 time with any arguments received: 0 times with any arguments What am I doing wrong? | Outputting content onto rails website from Third Party API Posted: 23 Jan 2017 07:23 AM PST I am using the HTTParty Gem to access data from a third party API. I have set up the model to successfully retrieve/parse the data from the other website. What I do not know: What code is required in the controller to allow me to display the content in the view (and ultimately the website). Here is my code for the model file called representatives.rb require 'rubygems' require 'httparty' class Representative < ApplicationRecord include HTTParty base_uri 'whoismyrepresentative.com' default_params :output => 'json' format :json def self.find_by_zip(zip) get('/getall_mems.php', :query => {:zip => zip}) end end puts Representative.find_by_zip(92651).inspect Here are my Json results: <HTTParty::Response:0x7fa591c4a778 parsed_response={"results"=>[{"name"=>"Dana Rohrabacher", "party"=>"R", "state"=>"CA", "district"=>"48", "phone"=>"202-225-2415", "office"=>"2300 Rayburn House Office Building", "link"=>"http://rohrabacher.house.gov"}, {"name"=>"Darrell Issa", "party"=>"R", "state"=>"CA", "district"=>"49", "phone"=>"202-225-3906", "office"=>"2269 Rayburn House Office Building", "link"=>"http://issa.house.gov"}, {"name"=>"Barbara Boxer", "party"=>"D", "state"=>"CA", "district"=>"Junior Seat", "phone"=>"202-224-3553", "office"=>"112 Hart Senate Office Building", "link"=>"http://www.boxer.senate.gov"}, {"name"=>"Dianne Feinstein", "party"=>"D", "state"=>"CA", "district"=>"Senior Seat", "phone"=>"202-224-3841", "office"=>"331 Hart Senate Office Building", "link"=>"http://www.feinstein.senate.gov"}]} So what do I need to put in the representatives_controller.rb as well as the view files at this point? Thanks | Rails Spree shipping. Posted: 23 Jan 2017 06:53 AM PST How I can combined this two shipping into a single without double price for shipping. Thnks | Specify Unicode Character in Regular Expression Posted: 23 Jan 2017 07:30 AM PST How can I create a ruby regular expression that includes a unicode character? For example, I would like to the character "\u0002" in my regular expression. | How do I display an image from an attachment? Posted: 23 Jan 2017 06:46 AM PST I'd like to display an image, that I uploaded with CarrierWave, in the following code block. And ow can I define the image size? <%= simple_format(@employer.name) %> <% if @employer.attachment.present? %> <h4>Attachment</h4> <div class="attachment"> <p> <%= link_to File.basename(@employer.attachment.url), @employer.attachment.url %> (<%= number_to_human_size(@employer.attachment.size) %>) </p> </div> <% end %> | Cannot install gem march_hare Posted: 23 Jan 2017 06:17 AM PST I tried adding this to my Gemfile: gem 'march_hare', '~> 2.22' Using bundle install I got this message: Could not find gem 'march_hare (~> 2.22)' in any of the gem sources listed in your Gemfile or available on this machine. On the topmost line in my Gemfile, I have this : source 'https://rubygems.org' When I manually visit the rubygems and I m able to find this gem here : https://rubygems.org/gems/march_hare How do I install this gem? I don't understand what is happening. | Ruby on Rails - Default ascending sort bootstrap table for the filtered column Posted: 23 Jan 2017 05:57 AM PST I'm a newbie in Rails, I want sort data in some code and I stuck... I have a problem with the default sorting (ASC) on my bootstrap table. I want to sort data by the 'Expires' column, but I'm not sure how in case of filters add attributes which will refer to only one column. Data-field added to the %th makes the whole table filled with dates... Can somebody help me? _index.haml %table.table-striped#users-table(data-toggle="table" data-search="true" data-classes="table table-no-bordered" data-show-columns="true" data-locale="pl-PL" data-pagination="true" data-sort-order="asc" data-sort-name="expired") %thead %tr - index_columns(params[:filter]).each do |column| %th(class="#{index_columns_head[column][:class]}" data-sortable="true" data-field="expired") = index_columns_head[column][:head] %tbody (..) :javascript $('#users-table').bootstrapTable(); users_helper.rb def index_columns_head { name: { class: "col-lg-7", head: "Name" }, active_subscriptions: { class: "col-lg-2", head: "Subscriptions" }, expired: { class: "col-lg-2", head: "Expires" }, clients_count: { class: "col-lg-2", head: "Customers" }, options: { class: "col-lg-2", head: "Option" } } end def index_columns_content(user) { name: head(user), active_subscriptions: subscriptions_count(user), expired: subscription_expired(user), clients_count: User.of_agent(user).count, options: link_to('New Order', new_user_order_path(user_id: user)) } end | Get values from Javascript object in Rails controller Posted: 23 Jan 2017 06:45 AM PST I'm fairly new to Rails but I have a situation where a user can create a vacancy and select modules for that vacancy by dragging en dropping modules. Everytime something has changed (a module has been added/removes to the vacancy of the order has changed) I send a javascript object to the rails controller through AJAX and I want to extract the values from this object and story them in my DB. My object will look like this: addedModules = { module: [ {module_id: '1', name: 'first-module', width: '3', height: '1', position: '1'}, {module_id: '5', name: 'fifth-module', width: '1', height: '1', position: '2'}, {module_id: '3', name: 'third-module', width: '4', height: '1', position: '3'}, ] }; In my controller I would like to go through every module and extract their module_id, name, etc. AJAX block: $.ajax({ type: "POST", url: "../../../vacancies/" + <%= params[:vacancy_id] %> + "/update_with_modules", data: "addedModules=" + addedModules }).done(function (response) { console.log(response); }); Is there a way to do so or is there a better solution? | Rails form with dynamic test bank Posted: 23 Jan 2017 05:33 AM PST I'm looking to create a question bank where the test creator can specify the number of question they would like to see for each category of the form. Currently I loop through all of the question to build the form, and I'm not sure how to simply pull out only x number of questions per category. @questions = AuditQuestions.where(question_active: 'Y', audit_forms_id: session[:audit_forms_id]).order(question_order_number: :asc) Table structure: id audit_forms_id question_category question_title question_text question_order_number question_active | data must be a two dimensional array of cellable objects Posted: 23 Jan 2017 05:29 AM PST I'm trying to print some data in a table using a condition, but it returns the following error: data must be a two dimensional array of cellable objects data = [["Lançamento"]] data += @lancamentos.map do |lancamento| if lancamento.tipo == 'DESPESA' [ lancamento.descricao_lancamento, lancamento.valor ] end end pdf.table data | Slimpay Illegal state Error when try to call orders.get_mandates method Posted: 23 Jan 2017 04:55 AM PST | Difference between broadcast , broadcast_to and broadcast_for in rails 5 Posted: 23 Jan 2017 04:51 AM PST From the Rails Guide I found following three code snippets ActionCable.server.broadcast("chat_#{params[:room]}", data) This simple broadcast sends the data to a specific chat room while broadcast_to as shown below seems to send data to all chatrooms within a channel to which current user is subscribed . WebNotificationsChannel.broadcast_to( current_user, title: 'New things!', body: 'All the news fit to print' ) Here is another type of broadcast broadcast_for - for which i couldn't get any example . My question is what is actual difference between these three and when to use each of 'em - thanks in advance | Why is this map not working? Posted: 23 Jan 2017 04:42 AM PST I have a list of associado , and I want to select only the ones where eh_proprietario returns true . This is the mapping: @possiveis_associados = associados.map { |e| e if e.eh_proprietario} If I add a puts "#{e.eh_proprietario}" I can see it return true for two instances, but in my view, when I try to use this collection, I get an error because @possiveis_associados is nil. <%= m.select :associado_id , options_from_collection_for_select(@possiveis_associados, :id, :razao_social), {include_blank: false}, {class: 'form-control'}%> What am I doing wrong here? | Selenium does not execute javascript Posted: 23 Jan 2017 04:46 AM PST I am using capybara with Selenium as its driver. I am trying to click on an element, which when clicked it will reveal a div, but the click never invokes javascript to do just that. Below is the code I have scenario 'currently used transport mode cannot be re-selected' do expect(page).to have_css("h2.summary") expect(find('h2.summary').text).to eq("Single event") expect(page).to have_content("Change journey") page.click_link("Change journey") expect(find('#travel-times-preview').visible?).to be_truthy # FAILS here because of previous step not working end error message Capybara::ElementNotFound: Unable to find css "#travel-times-preview" html <a class="change-journey gray-text" href="#">Change journey</a> javascript code to execute $(".change-journey").on("click", function(e){ var target = $(this).data("preview-target"); $('[data-preview-toggle="'+ target +'"]').toggleClass("hidden"); if($(this).text().indexOf('Change journey') > -1){ $(this).text("Close Preview"); }else{ $(this).text("Change journey"); } e.preventDefault(); }); While i can see the link being clicked, the underlying javascript is not executed. | How to use two different method with the same "name" from two different gems on the same rails model? Posted: 23 Jan 2017 05:10 AM PST The app (rails 4.2.7) i'm working on uses both carrierwave and paperclip for uploading image for two different fields on the same data model User (schema below). create_table "users", force: :cascade do |t| t.string "email" t.string "first_name", limit: 255 t.string "last_name", limit: 255 t.string "avatar_file_name", limit: 255 t.string "avatar_content_type", limit: 255 t.integer "avatar_file_size" t.datetime "avatar_updated_at" t.string "cv_file" end The avatar field is a paperclip object and cv_file is a carrierwave uploader. Now, for background processing of cv_file field, i'm using carrierwave_backgrounder gem and for avatar field i'm using delayed_paperclip gem. Both of these gems exposes process_in_background to process the image upload to background. So my User model looks like: class User < ActiveRecord::Base # carrierwave mount_uploader :cv_file, CvFileUploader process_in_background :cv_file # paperclip has_attached_file :avatar, :default_url => "default-avatar.png", :styles => { :thumb => ['100x100#', :jpg, :quality => 80] } process_in_background :avatar, processing_image_url: "default-avatar.png" # ... end I'm getting this error while trying to access any page on the app. undefined method `remove_avatar?' for Did you mean? remove_cv_file? Any help will be greatly appreciated. Thank you! | LIKE query with MySQL always return nil Posted: 23 Jan 2017 04:05 AM PST First of all, I'm using rails 4. What I'm trying to do is search some usernames in my MySQL database. But whatever my query is, @search is nil, and the result is 404. Here's my code. I tried several changes with my params[:query] such as "%#{params[:query]}%" or just params[:query] with out "%". But it still didn't work Any help will be appreciated. def search_user @searh=User.where('username LIKE ?', "%"+params[:query]+"%").all if @search == nil then head 404, content_type: "text/html" else render json: @search.to_json, status: 200 end end | How do I count within nested resourced and display the results? Posted: 23 Jan 2017 04:06 AM PST I am building a job board in rails based on PostgreSQL. I want to count and display the amount of job offers per employer on the index of the employer page. What is the code for this kind of count? I created a nested resource, and associated my employer and offer model, by: class Employer < ActiveRecord::Base has_many :offers, dependent: :delete_all end | Rails eager loading associations Posted: 23 Jan 2017 04:14 AM PST I have two models MSellingStaff and MPosition #m_selling_staff.rb class MSellingStaff < ActiveRecord::Base belongs_to :m_position end #m_position.rb class MPosition < ActiveRecord::Base self.primary_key ='pos_id' has_many :m_selling_staffs, :foreign_key => 'emp_pos_id' end I have an attribute pos_short_name in m_position . When I try @sellers = MSellingStaff.includes(:m_position).all @sellers.first.pos_short_name I am getting undefined method `pos_short_name' for #MSellingStaff:0x0000000651a5d0 and when I try @sellers.first.m_position.pos_short_name I am getting undefined method `pos_short_name' for nil:NilClass In the rails console I can see that the SQL generated for @sellers = MSellingStaff.includes(:m_position).all is MSellingStaff Load (0.6ms) SELECT "m_selling_staffs".* FROM "m_selling_staffs" MPosition Load (0.2ms) SELECT "m_position".* FROM "m_position" WHERE "m_position"."pos_id" IN ('') What am i doing wrong? thanks in advance | Developing API using Rails 5.x Posted: 23 Jan 2017 03:30 AM PST I need to develop a Rails based API which takes in a JSON input with parent and child data (Customer and his Cars), and stores them in User and Car tables respectively. I am currently learning from Developing API using Rails 5 However, the above example uses two Controllers for each table. I need one single Transaction. Are there any resources to learn how to save in multiple tables in one block using Rails 5 API ? | Rails: build in certain order Posted: 23 Jan 2017 03:12 AM PST I create two addresses home address and semester using build, nested attributes and fields_for like below def new @user.adresses.build(home_adress: true) @user.adresses.build(semester_adress: true) end def edit @user.adresses.build(home_adress: true) if @user.adresses.where(home_adress: true).blank? @user.adresses.build(semester_adress = true) if @user.adresses.where(semester_adress: true).blank? end and the form looks like this <%= f.fields_for :adresses do |builder| %> <%= render 'adress', f: builder %> <% end %> Now the problem is, if a user only add semester address, not home address during the registration, then when that user tries to edit the address, semester address shows first and then home address after that. But for me, the order is very important. So I have to show home address first even if it blank and then semester address. How can I do this? Edit: I figured the above thing may not be clear. So here is another relevant example of what I need. If I have a new action like this def new @user.adresses.build(home_adress: true) @user.adresses.build(semester_adress: true) end and in the edit action I try to add more addresses as below def edit @user.adresses.build(office_adress: true) @user.adresses.build(parents_adress: true) @user.adresses.build(home_adress: true) @user.adresses.build(semester_adress: true) end This does not build in order as I expect. Instead if a user home address and semester address build first since they are already in database and the new office and parents address build later since they are new builds. But I want them to build in the order. How can I do this? | JavaScript append Rails erb code Posted: 23 Jan 2017 03:36 AM PST I got a complicated select block which was written by rails erb , but now I need to rewrite it into jQury using append . The select block is like this <select id="mission_reward" name="mission_reward" class="select_reward"> <option value="0"><%=t('mission.create_panel.no_reward')%></option> <% @monsters.each do |monster|%> <option data-img-src="<%=monster.url%>" data-cost='<%=monster.need_q_point%>' value="<%=monster.id%>"> <%= monster.name %> </option> <% end%> </select> I've written some code following html <div class='select_block'></div> <script type="text/javascript"> $(function() { $('select_block').append(AppendReward()); }); </script> js function AppendReward(){ return "<select id=\"mission_reward\" name=\"mission_reward\" class=\"select_reward\"> \ <option value="0"><%=t('mission.create_panel.no_reward')%></option> \ <% @monsters.each do |monster|%> \ <option data-img-src="<%=monster.url%>" \ data-cost='<%=monster.need_q_point%>' \ value=\"<%=monster.id%>\"> \ <%= monster.name %> \ </option> \ <% end%> \ </select>" } But it seems to fail, I am not familiar with JavaScript, is it wrong with the syntax? | Too may redirects rails respond_to Posted: 23 Jan 2017 03:11 AM PST I have a controller action method that gets all records of establishments from the DB, I then want to share this response with a external entity which is a RhoMobile application, i used respond_to to format the response to JSON. def index @establishments = Establishment.index(params).includes(:assessor) @json_establishments = Establishment.all respond_to do |format| format.html { redirect_to(establishments_url) } format.json { render json: @json_establishments.as_json } end end When i navigate to this action i get an error net::ERR_TOO_MANY_REDIRECTS in chrome developer tools on the console tab. When i remove the { redirect_to(establishments_url) } next to the format.html it's working with a status of 406 (Not Acceptable) but if i would use the search in the action view that i created and click the browsers back button, i get something like: ActionController::UnknownFormat in EstablishmentsController#index ActionController::UnknownFormat <div class="source hidden" id="frame-source-0"> <div class="info"> Extracted source (around line <strong>#219</strong>): </div> instead and when i refresh the page i get the expected view. | JSONAPI testing with rspec and Airborne Posted: 23 Jan 2017 02:56 AM PST Hello i have problem with testing JSONAPI with rspec and airborne. GET model below https://i.stack.imgur.com/Cyf75.png Im testing it this way https://i.stack.imgur.com/Y9rHt.png Rspec output: Failures: 1) GET on /contacts should validate types Failure/Error: expect_json('books.0', title: 'The Great Escape') Airborne::PathError: Expected NilClass to be an object with property 0 # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:21:in `rescue in block in get_by_path' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:18:in `block in get_by_path' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `each' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `each_with_index' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `get_by_path' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/request_expectations.rb:137:in `call_with_path' # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/request_expectations.rb:18:in `expect_json' # ./book_resource.rb:10:in `block (2 levels) in <top (required)>' # ------------------ # --- Caused by: --- # NoMethodError: # undefined method `[]' for nil:NilClass # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:57:in `process_json' Finished in 0.03121 seconds (files took 0.17681 seconds to load) 1 example, 1 failure | How to create force-directed graph of each individual area? Posted: 23 Jan 2017 01:55 AM PST I am fairly new to rails and to D3.js but have been working on creating forced-directed graphs. I would like to know if anyone can help me find a way to make force-directed graphs for individual 'areas' or 'groups'. So for example, I have 6 groups of devices in a network, I am displaying these in one big graph (or topology) but I would like to also display each group individually as its own graph on separate pages. This is as far as I have got but the @links section does not work as it should and I am stuck for ideas. def group_1 @devices = Device.where("area = 'Group 1'") @get_devices = @devices.map do |device| {"id" => device.id, "name" => device.name, "group" => device.area } end @links = Link.where("from_device_id >== :from_id || to_device_id >= :to_id", {from_id: @devices.id, to_id: @devices.id}) @get_links = @links.map do |link| {"source" => link.from_device.id, "target" => link.to_device.id} end @all_data = { "nodes" => @get_devices, "links" => @get_links} render json: @all_data end This may be a stupid question, so I apologise but any help would be greatly appreciated. Many Thanks Faye | form_for > f.submit, How to only alert at update action. Posted: 23 Jan 2017 01:35 AM PST How would one set this up so it only pop's up at update action and not create? = f.submit, data: { confirm: "you are about to update object, are you sure?" } | How to view rails/routes for a rails engine in the browser Posted: 23 Jan 2017 02:32 AM PST I have a rails engine, which is mounted in dummy/config/routes.rb using mount Handicap::Engine => "/handicap" In the engine, I have a number of controllers, and when I start a rails server in the dummy directory these routes are active e.g. /handicap/tees/index responds. However, when I go to /rails/routes it only shows: handicap_path /handicap Handicap::Engine rails_routes_path GET /rails/routes(.:format) sextant/routes#index sextant_engine_path /sextant Sextant::Engine I can list them using rake routes , but my normal work flow is to list them in the browser. How do I list the engine routes in the browser? |
|