Ruby on Rails: how to pass an instance variable from a controller to another controller via a form Posted: 23 Aug 2016 07:57 AM PDT I am new to rails and web development, so please bear with me. I have been trying to build an automated deployment system of sorts for a site. I have a form in my home page which gets a name field for a site_name model, and I am trying to pass this name (and also site_name instance) to another controller which makes the deployment. However, I couldn't manage to pass the name correctly. How can I pass an instance variable from a from to another controller? These are the files I use FYI home.html.erb <div class="center jumbotron"> <h1>Welcome to the Sample App</h1> <div class="input-group"> <%= form_for @site_name, url: {action: "instantiate", controller: "script_execute"}, html: {method: "get"} do |f| %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.submit "Create my account", class: "btn btn-primary" %> <% end %> </div> <%= link_to "Sign up now!", instantiate_path, class: "btn btn-lg btn-primary" %> </div> script_execute_controller.rb (which contains instantiate action) class ScriptExecuteController < ApplicationController def instantiate site_name = @site_name.name @hostname = 'myhostname' @username = 'myusername' @password = 'mypassword' @cmd = "yes #{site_name} | ./denemescr.sh" begin ssh = Net::SSH.start(@hostname, @username, :password => @password) res = ssh.exec!(@cmd) ssh.close puts res end redirect_to root_url end end static_pages_controller.rb (controller for the home page) class StaticPagesController < ApplicationController def home @site_name = SiteName.new end end |
force Download a file from AWS s3 rails Posted: 23 Aug 2016 07:49 AM PDT I'd like to know if someone know a way to force download a file from AWS. For some security reason I've transfer some files from my google drive to s3. For the google docs there is an url that permit to download the file with his id. Maybe there is a similar process for s3? I'd like that the users of my rails app can download the file on a simple link. Thank you! |
Hartl's railstutorial.org Chapter 5, exercise 2 Posted: 23 Aug 2016 07:56 AM PDT Upon creating this file: test/helpers/application_helper_test.rb , and running: 'rails test' I'm getting this failure: AIL["test_full_title_helper", ApplicationHelperTest, 0.7209667120041559] test_full_title_helper#ApplicationHelperTest (0.72s) --- expected +++ actual @@ -1 +1 @@ -"Help | Ruby on Rails Tutorial Sample App" +"Ruby on Rails Tutorial Sample App" test/helpers/application_helper_test.rb:6:in `block in <class:ApplicationHelperTest>' Having browsed similar questions, albeit questions over a year old (and using older Rails code), I'm none the wiser as to how to rectify this failure. I am clearly a Ruby noobie, so please be gentle :) any help would be greatly appreciated static_pages_controller_test.rb: require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get home" do get root_path assert_response :success assert_select "title", "Ruby on Rails Tutorial Sample App" end test "should get help" do get help_path assert_response :success assert_select "title", "Help | Ruby on Rails Tutorial Sample App" end test "should get about" do get about_path assert_response :success assert_select "title", "About | Ruby on Rails Tutorial Sample App" end test "should get contact" do get contact_path assert_response :success assert_select "title", "Contact | Ruby on Rails Tutorial Sample App" end end and the offending file: require 'test_helper' class ApplicationHelperTest < ActionView::TestCase test "full title helper" do assert_equal full_title, "Ruby on Rails Tutorial Sample App" assert_equal full_title("Help"), "Help | Ruby on Rails Tutorial Sample App" end end |
NameError in DevicesController#create Posted: 23 Aug 2016 07:58 AM PDT I am trying to save embedded data in documents. A user can have many devices under his account. I am using User 1-N Devices embedding. But while saving my data I get this error: undefined local variable or method `user' for #< DevicesController:0x007fe0011277b0> user.rb class User include Mongoid::Document # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" field :name, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Confirmable # field :confirmation_token, type: String # field :confirmed_at, type: Time # field :confirmation_sent_at, type: Time # field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts # field :unlock_token, type: String # Only if unlock strategy is :email or :both # field :locked_at, type: Time embeds_many :devices end device.rb class Device include Mongoid::Document field :DevUI, type: String # field :user_id, type: String embedded_in :user # embeds_many :devicedatas end devices_controller.rb class DevicesController < ApplicationController before_action :authenticate_user! def index @devices = Device.all end def new @device = Device.new end def create @device = Device.new(device_params) user.devices.append(@device) respond_to do |format| if user.save format.html { redirect_to @device, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @device } else format.html { render :new } format.json { render json: @device.errors, status: :unprocessable_entity } end end end def show end # def show # @device_data = DeviceData.find(params[:id]) # end private def device_params params.require(:device).permit(:DevUI) end end |
Ruby Dashing Gem Displayed /events Data on Widget Page Posted: 23 Aug 2016 07:39 AM PDT I have a page which has 6 different metrics graphed on it and dynamically pulls the data for ~1000 different locations. An example would be https://example.com/huds/miami and would have 6 graphs related to Miami on it. Occasionally instead of displaying the pretty graphs the page will instead display all of the data from /events and then the raw html of the page beneath of it. This seems to happen after having the page open for ~1 hr around 20% of the time. Is this a known bug and something I can solve? |
Rails - Add games Association to users Posted: 23 Aug 2016 08:01 AM PDT I'm building an association between Users and Games, Users can favorite or associate Games to their profile. But I got an issue with the routes or the link (I guess, maybe its something else). I have a join table between Users and Games : Game_User with games ID and User ID The association is working fine in the console when I do this. @user = User.find(session[:user_id]) @game = Game.find(params[:id]) @user.games << @game games_controller.rb: def favorite game = Game.find(params[:id]) current_user.games << game flash[:notice] = 'You favorited #{@game.name}' redirect_to games_url end routes.rb get "games" => "games#index" post "games/:id" => 'games#favorite' And I would like to do the same with my link. Here is the list of the games, and for each a link to favorite them : <% if current_user %> <% @games.each do |game| %> <tr> <td><%= game.name %></td> <td><%= game.plateform %></td> <td><%= game.typegame %></td> <td><%= link_to 'Show', game %></td> <td><%= link_to 'Edit', edit_game_path(game) %></td> <td><%= link_to 'Destroy', game, method: :delete, data: { confirm: 'Are you sure?' } %></td> <td> <%= link_to "favorite", games_path, type: "favorite", method: :post %> </td> </tr> <% end %> <% end %> My problem is : Creating the association between user and game(s) , when i click on the link Favorite, it's generating a new Game (def create game.new ... ) |
Reloading to du deleting a rails model Posted: 23 Aug 2016 07:24 AM PDT I'm trying to dynamically create and delete rails models. Creation works but not deletion. I've tried deleting it as a Constant but it is still present as a rails subclass: Object.send(:remove_const, :ModelToBeDeleted) # Check it's gone from Object Object.constants.include? :ModelToBeDeleted # => false # But it is still in rails: ActiveRecord::Base.subclasses # returns [ModelToBeDeleted(....)] I've then tried using the callback in the finisher, which does this when reloading in development: ActiveSupport::DescendantsTracker.clear ActiveSupport::Dependencies.clear But it has no effect. Can anyone help me on how to do this? Thanks Nick |
Rails unknown format on AJAX Posted: 23 Aug 2016 07:47 AM PDT I'm trying to implement a very simple file form using the remotipart gem. Most of my files are the exact same as the tutorial ones: timeline.html.erb : <%= form_tag new_feed_path(:format => "js"), remote: true, :html => { :multipart => true } do |f| %> <%= hidden_field_tag :brief_id, @brief.id %> <%= file_field_tag :file %> <%= submit_tag "Send", class: "btn btn-success" %> <% end %> briefs_controller.rb def new_feed puts params respond_to do |format| format.js end end new_feed.js.erb alert('success!'); <% if remotipart_submitted? %> alert('submitted via remotipart') <% else %> alert('submitted via native jquery-ujs') <% end %> But everytime I submit the form, I get the following error in the logs: Processing by ResourcesController#create as HTML Completed 406 Not Acceptable in 14ms ActionController::UnknownFormat - ActionController::UnknownFormat: Did I miss something ? I know ajax file upload can be tricky on RoR, but remotipart seems to be a viable solution. EDIT I managed to fix the first issue by adding :format => "js" , but now I face another problem: none of the form datas are sent. In fact, here are the sent params: {"controller"=>"briefs", "action"=>"new_feed"} |
When run test with Rspec I have error => Net::OpenTimeout: execution expired Posted: 23 Aug 2016 07:23 AM PDT I wrote few basics tests. When I try to run it I have those errors : Failures: 1) Direction has a valid factory Failure/Error: FactoryGirl.create(:direction).should be_valid Net::OpenTimeout: execution expired # ./spec/models/direction_spec.rb:6:in `block (2 levels) in <top (required)>' 2) Ingredient has a valid factory Failure/Error: FactoryGirl.create(:ingredient).should be_valid Net::OpenTimeout: execution expired # ./spec/models/ingredient_spec.rb:6:in `block (2 levels) in <top (required)>' 3) Recipe has a valid factory Failure/Error: FactoryGirl.create(:recipe).should be_valid Net::OpenTimeout: execution expired # ./spec/models/recipe_spec.rb:6:in `block (2 levels) in <top (required)>' This is one of my failing test : require 'rails_helper' describe Recipe do it "has a valid factory" do FactoryGirl.create(:recipe).should be_valid end it { should have_many(:ingredients) } it { should have_many(:directions) } it { should have_many(:taggings) } it { should have_many(:tags) } it { should belong_to(:user) } end rails_helper : # This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' require 'shoulda/matchers' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migration and applies them before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include FactoryGirl::Syntax::Methods # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end spec_helper : ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end I have no idea about where this error can come from. I searched on stackoverflow and internet, it looks like it's an email server error. But I just begun my app, there is no mailer for the moment, just 5 models and those basic tests. I don't know which files could be usefull to answer this question. Do not hesitate to tell me |
Prevent Rails from converting JSON to a String? Posted: 23 Aug 2016 07:14 AM PDT My Rails app broadcasts a set of records via Action Cable, ActionCable.server.broadcast 'model_channel', models: (ApplicationController.render 'models/index.json', assigns: { models: Model.all }) I'm calling ApplicationController.render to ensure jbuilder is invoked (I'm adding custom fields in my models/index.json.jbuilder file). All works fine EXCEPT that the broadcast argument is converted to a string, thus I need to call JSON.parse(data['models']) in order for the data to be used in the JavaScript handler. Is there anything I can do on the Ruby side to avoid string-ifying my payload and then parsing it on the client side? |
Hide table header if there is no column attribute - Ruby on rails Posted: 23 Aug 2016 07:35 AM PDT Here is a index.html.erb. How do I hide the table header, such as Remark, with a method when no records exists in remark attribute column? Preferably without using JavaScript. index.html.erb <thead> <tr class="tr-head"> <td>Date</td> <td>Description</td> <td>Amount</td> <td>Discount</td> <td>Paid</td> <td>Balance</td> <td>Remark</td> </tr> </thead> However I am able to hide the remark attribute values like as below ; _aslani361.html.erb <% if !aslani361.remark.blank? -%> <td class="col-1"><%= aslani361.remark %></td> <% end %> aslani361.rb class Aslani361 < ActiveRecord::Base end Any suggestions are most welcome. Thank you in advance. |
How to force nginx to include Content-Length header on HEAD requests Posted: 23 Aug 2016 07:31 AM PDT How do you configure nginx to return a valid Content-Length header when responding to a HTTP HEAD request? Currently my server returns this: curl --head http://example.com/myfile.xml HTTP/1.1 200 OK Date: Tue, 23 Aug 2016 13:49:46 GMT Content-Type: text/xml Set-Cookie: __cfduid=da2daeaa59809916192f7ac0645d3a3e91471960186; expires=Wed, 23-Aug-17 13:49:46 GMT; path=/; domain=.example.com; HttpOnly Last-Modified: Mon, 22 Aug 2016 16:20:26 GMT Vary: Accept-Encoding ETag: W/"57bb264a-5442b26a" Expires: Thu, 31 Dec 2037 23:55:55 GMT Cache-Control: max-age=315360000 Access-Control-Allow-Origin: * Access-Control-Request-Method: * Cache-Control: public Server: cloudflare-nginx CF-RAY: 9dac40-LHR X-Cache: MISS from Squid Via: 1.1 Squid (squid/3.2.14) I must send the Content-Length header with the response to HEAD (if I don't, the service that checks that URL will never see that the file was changed, and will not download the new version). How do you set it up? |
Externa I18n locale path Posted: 23 Aug 2016 06:48 AM PDT I have a database based translation system for my Rails app which works great except for the fact it, obviously, sends a LOT of requests to the database. I can only use cache to a certain amount of the requests but a feasable option for me is to export the translation table into a YAML-file, which can be read by the system. The problem I have is that my app is on Heroku and you cannot write to that file system, I have to use AWS (using Carrierwave) to store the locale-files. I can write to AWS but I cannot get my Rails app to read the locale-files from my AWS-storage. I have tried the below setting (which is just trial and error) but it doesn't work. Application.rb config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] config.i18n.load_path += Dir["https://s3-eu-west-1.amazonaws.com/myapp/locales/", '*.{rb,yml}'.to_s] config.i18n.available_locales = [:en, :se] How can I setup my app so that the locale-files (e.g. https://s3-eu-west-1.amazonaws.com/myapp/locales/en.yml) are read from this external source? Is it even possible? If not, is there a workaround? |
Using rails as the omniauth provider Posted: 23 Aug 2016 06:57 AM PDT I'm not entirely sure what to google. It seems everything I have googled just show me links to how to leverage omniauth to authenticate with other sites(facebook, twitter, github etc etc). That's simple and easy. What I want is the how to build that feature in a rails app, the functionalities that those sites (facebook, twitter, github) have that allow third party auth. Here's the feature I'd like to build: I have two separate applications, applications A and B. Let's say application A is the rails app that I want providing the authentication. And application B is using omniauth to login through application A. How do I get started building that feature for application A? Now, that's a loaded question, but if anyone could point to a resource I could start with that would be amazing! Thanks. |
What is meant by JSON end point in Rails? Posted: 23 Aug 2016 07:05 AM PDT What is meant by "create JSON API end point"? |
How remove first match in gsub? [duplicate] Posted: 23 Aug 2016 06:37 AM PDT This question already has an answer here: I have this 2016-05-20T13:36:29.835, CTF3D57C and i want this 2016-05-2013:36:29.835, CTF3D57C Just remove first T character. How do this? |
Rails API: Adding array of objects to json return Posted: 23 Aug 2016 07:44 AM PDT I'm using the built-in API with Rails 5. I'm learning to write APIs with Rails and I'm trying to figure out how to add a property to my json return that is an array of objects. I've got a model for Users and Posts. What I would like to do is return all the posts associated with a users. What I've done is in posts_controller.rb I've got a method that gets the userID form the URL and returns json that looks like: [{"id":1,"content":"My first post!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}},{"id":2,"content":"Rails School is awesome!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}}] But what I want is to return that looks like this: { firstname: "Jody", lastname: "White", email: "whatever", posts: [{ "id":1,"content":"My first post!" }, { "id":2,"content":"Rails School is awesome!" } ] } How do I go about, or can I, getting the data to return like that? user.rb model class User < ApplicationRecord attr_accessor :fullname_firstname_first has_many :posts def fullname_firstname_first fullname_firstname_first = firstname + " " + lastname end end post.rb model class Post < ApplicationRecord belongs_to :user end |
Getting value formatted as ["example"] - Ruby on Rails Posted: 23 Aug 2016 07:54 AM PDT I'm working with NET-LDAP API using Ruby on Rails. @ldap.search( :base => @treebase, :filter => @filter ) do |entry| entry.cn When I get the entry.cn value it comes formatted as ["example"] How do I get this value without the characters [" "] ? |
How can I customize links/bookmarks in my pdf in Ruby on Rails using wkhtmltopdf & wicked_pdf? Posted: 23 Aug 2016 06:16 AM PDT How can I customize links/bookmarks in my pdf in Ruby on Rails using wkhtmltopdf & wicked_pdf? It seems to auto-load my book marks panel by assuming the links with , , etc. tags. However, I'm wanting to specify my own bookmarks without them corresponding to existing heading tags. Is there a way to set these through code as the pdf document is being generated? |
how do i convert hash symbols Posted: 23 Aug 2016 06:58 AM PDT i have a following formatted hash {:name=>"testname", :data=>"[209.04, 110.97, 38.83, 234.18]"} i want to convert this to {name: "testname", data: [209.04, 110.97, 38.83, 234.18]} |
Rails/SQL query with grouping Posted: 23 Aug 2016 06:33 AM PDT I just don't understand grouping and how to fix this. I'm getting the error: column "current_matches_unordered.id" must appear in the GROUP BY clause or be used in an aggregate function. @new_matches = Character.select('"current_matches_unordered".*') .from("(#{@current_matches_unordered.to_sql}) AS current_matches_unordered") .joins(" INNER JOIN matchrelationships ON current_matches_unordered.id = matchrelationships.character2_id AND #{character_id} = matchrelationships.character1_id GROUP BY matchrelationships.updated_at ORDER BY matchrelationships.updated_at DESC ") If I change the GROUP BY line to: GROUP BY matchrelationships.updated_at, current_matches_unordered.id it then whinges that current_matches_unordered.created_at must appear in the GROUP BY clause. And if I add that, it whinges about current_matches_unordered.updated_at . I can't win. |
Rails 4 remote true form request (for an ajax loader) with browser url updated Posted: 23 Aug 2016 06:16 AM PDT I have a rails form that fires ajax by remote true as follows. = form_tag(root_path, method: "get", remote: true) do ... Works fine and all but how can I achieve the browser url to be updated with the search params ? What I want to achieve is that after successful response, the browser should be updated with the correct url as in normal rails html request. Eg. localhost:3000/my_controller?status=canceled&search=mysearchkey&commit=Search |
rails update object name after instantiate Posted: 23 Aug 2016 05:52 AM PDT I have an object created as follows: myObject = MyModule::MyClass.new(user).some_class where the module/class looks like such: module MyModule class MyClass def initialize(user) @user = user otherclass_to_set_variable end def some_class output = 'Page::' + otherclass_variable end end end This is great and returns 'Page::OtherViariable'. What I want is to update 'Page::OtherVariable' to 'Page::NewVariableName'. Is this possible? I want to update it because if the output variable 'OtherViariable' is one of three viariables, I need a new syntax. I know I can change some_class but right now that's not what I'm hoping to do. Thanks. |
Acordion sidebar in spree taxons_tree Posted: 23 Aug 2016 06:18 AM PDT I am creating an acordion sidebar menu in taxonomies. Everything works good except one thing: When I click on the first parent element it works, and taxons_tree is hidden. But when I click on the second, third and etc, only the first taxons_tree is hidden. Here is my code of _taxonomies.html.erb: <% max_level = Spree::Config[:max_level_in_taxons_menu] || 1 %> <nav id="taxonomies" class="sidebar-item" data-hook> <% @taxonomies.each do |taxonomy| %> <% cache [I18n.locale, taxonomy, max_level, @taxon] do %> <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class='taxonomy-root'><a data-toggle="collapse" data-parent="#accordion" href="#root_taxon"><span id="main_icon" class="glyphicon glyphicon-align-justify"> </span><%= Spree.t(:shop_by_taxonomy, taxonomy: taxonomy.name) %></a></h4></div></div></div> <%= taxons_tree(taxonomy.root, @taxon, max_level) %> <% end %> <% end %> </nav> and my taxons_tree method of frontend_helper.rb: def taxons_tree(root_taxon, current_taxon, max_level = 1) return '' if max_level < 1 || root_taxon.leaf? content_tag :div, id:'root_taxon', class: 'list-group panel-collapse collapse in' do taxons = root_taxon.children.map do |taxon| link_to(seo_url(taxon), class: 'list-group-item'){content_tag(:span, " ", class: "glyphicon glyphicon-chevron-right") + taxon.name} + taxons_tree(taxon, current_taxon, max_level - 1) end safe_join(taxons, "\n") end end I understand that href from _taxonomies.html.erb must be the same with my content_tag id. You can see I tried too use variable, but it works the same only for the first one. It must change for every new taxon, but i dont know how it do right. Source code for acodrdion menu I take from here: http://bootsnipp.com/snippets/featured/accordion-menu maybe it will help you. Here it is implemented very simply just changing #collapseOne, #collapseTwo, etc. |
can't add custom script in overcommit gem Posted: 23 Aug 2016 06:07 AM PDT I'm not sure if this is something I should post in the official repository issue(I sometimes see 'question' tag there). But if you think this is the appropriate place to ask this, would be great if someone could help me out. I've been trying to add a custom script in overcommit gem with no luck. What it says in the official document is to add lines in .overcommit.yml: PostCheckout: CustomScript: enabled: true required_executable: './bin/custom-script' (so I've done so:) PrePush: customHook: enabled: true required_executable: 'custom-hook' and to put the script in .git-hooks directory in the project root. So I put this script in .git-hook dir for test: #custom-hook.sh echo hey Here's the sweet error message: Hook must specify a `required_executable` or `command` that is tracked by git (i.e. is a path relative to the root of the repository) so that it can be signed /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_signer.rb:39:in `hook_path' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_signer.rb:92:in `hook_contents' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_signer.rb:88:in `signature' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_signer.rb:61:in `signature_changed?' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_loader/plugin_hook_loader.rb:51:in `select' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_loader/plugin_hook_loader.rb:51:in `modified_plugins' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_loader/plugin_hook_loader.rb:55:in `check_for_modified_plugins' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_loader/plugin_hook_loader.rb:8:in `load_hooks' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_runner.rb:195:in `load_hooks' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_runner.rb:32:in `block in run' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/interrupt_handler.rb:84:in `isolate_from_interrupts' /Users/hiroki/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/overcommit-0.34.2/lib/overcommit/hook_runner.rb:28:in `run' .git/hooks/pre-push:79:in `<main>' Obviously, it complains it can't find the executable so I'm guessing the format isn't right, but there are little information out there and I'm stuck. |
Rails collection_select with join table Posted: 23 Aug 2016 07:02 AM PDT My tables: Person belongs_to and Room has_many Person My collection_select <%= collection_select(:inspection, :person_id, Person.involving(current_user), :id, :room_id) %> If I'm not wrong, in HTML it will be represented as the following code: <select name="post[person_id]"> <option value="<%= person.id %>"><%= person.room_id %></option> <% end %> </select> My point is that when a user submit the form I need send the Person Id value, but I need show on the drop down list the name of the rooms (in my example I showing the room.id) like that: <select name="post[person_id]"> <option value="<%= person.id %>"><%= room.name %></option> <% end %> </select> How can I do that? As I see I think that I need join person table with room table? If it is the solution, how can I do that? My person model: scope :involving, -> (user) do where("persons.id = ?", user.id) end My view <%= form_for @inspection do |f| %> <label>Select</label> <%= collection_select(:inspection, :person_id, Person.involving(current_user), :id, :room.id) %> <%= f.submit "Send" %> I tried to make it as clear as I could. |
When trying to create a new application record, returns nil Posted: 23 Aug 2016 05:38 AM PDT In UserController I need create a new Character . However, when using the Character.new returns nil . How to solve this problem? class UsersController < ApplicationController before_action :set_user, only: [:show, :update, :destroy] # POST /users def create character = Character.new # error where character.xp = 0 character.save ... render json: "success" end end Character's model is empty. class Character < ApplicationRecord end |
Where are ActiveRecord's comparison and bitwise interfaces? Posted: 23 Aug 2016 06:53 AM PDT I'm wondering why Active Record doesn't have a native/baked-in query interface for all bitwise and comparison operators. I've been using/supporting Rails since 2.3 and sort-of just waiting for it to arrive, but now that Rails 5 is out I feel like I need to ask, are OR , AND , gte , lte , etc., and all other bitwise and comparison operators going to be baked into Rails/AR natively? If not, I'm curious as to why? |
How to get tooltip in tabular form in Rails Posted: 23 Aug 2016 05:00 AM PDT I have a requirement in which tooltip has to be displayed in tabular can it be achieved through bootstrap or do I have to use some plugin? |
MongoDB - aggregation sort with group doesn't work Posted: 23 Aug 2016 06:12 AM PDT I have a query in Ruby on Rails for mongo: collection.aggregate([ { '$match' => { :user_id => '12345', :type => "view" } }, { '$group' => { :_id => '$room_id', 'message_time' => {'$first' => '$message_time'}, 'message_text' => {'$first' => '$message_text'}, 'from' => {'$first' => '$message.from_user'} } }, { '$skip' => 0 }, { '$limit' => 10 }, {'$sort' => {"message_time" => -1}} ]) In message time I have value like: 2016-08-22T12:49:29Z Even if I change sort to message_text it doesn't sort properly. Any ideas how to sort this? I was trying with putting everything from group into _id field and then sort by_id.message_time but still Its returning the wrong result. |
No comments:
Post a Comment