passing data from one rails application to another using apache camel-cxf-rest in servicemix Posted: 24 May 2016 07:09 AM PDT I have two Rails applications, lets say app1 and app2. I have to send some data from app1 to app2 using Apache ServiceMix(actually i have to send this data to 2 applications from ServiceMix - but for now lets stick to one application). I am using the camel-cxf-rest example inside ServiceMix/example/camel/ folder of ServiceMix. And in this there is the implementation of Person class as restful service(we can do POST of person and GET of person from other application.) So my app1 code looks like this: def post_demo url_string = "http://localhost:8989/rest/personservice/person/post/" xml_string = "<person><age>21</age><id>1</id><name>dharma</name> </person>" uri = URI.parse url_string request = Net::HTTP::Post.new uri.path request.body = xml_string request.content_type = 'text/xml' @response = Net::HTTP.new(uri.host, uri.port).start { |http| http.request request } end so i am making a post request from the app1 one and it successfully posts this person to the database in the servicemix. Now i use get from app2 as follows: def get_demo url = URI.parse('http://localhost:8989/rest/personservice/person/get/1') req = Net::HTTP::Get.new(url.to_s) @res = Net::HTTP::start(url.host, url.port){|http| http.request(req) } puts @res.body end So - till now what i am doing is making POST request from app1 and storing the data in the servicemix and making GET request from the app2 to get these data- But what i really want it whenever I make POST request to ServiceMix I want it to get forwarded to app2 so that i don't have to make GET request from app2. I dont have full idea but maybe apache camel routing is one solution.Thank you for any help in advance. |
how to export fromdate and todate in csv file Posted: 24 May 2016 07:12 AM PDT Attendance.rb def attendances_query(entity_code, fromdate, todate) to_date = todate.to_date.strftime('%Y-%m-%d') from_date = fromdate.to_date.strftime('%Y-%m-%d') ActiveRecord::Base.connection.execute <<-SQL select E.status as status, A.employee_code as emp_code,A.employee_name as emp_name, A.cc_code,A.cc_name,A.location_code,A.location_name,A.sub_location_code as subloc_code,A.sub_location_name as subloc_name, sum(case when A.status = 'Absent' then 1 else 0 end) as Absent_count, sum(case when A.status = 'Leave' then 1 else 0 end) as Leave_count, sum(case when A.status='W Off' then 1 else 0 end) as WeekOff_count, sum(case when A.status='C Off' then 1 else 0 end) as COff_count, sum(case when A.status='Present' then 1 else 0 end) as Present_shifts_count, count(distinct(case when A.status='Present' then A.date end)) as present_days from attendances A,employees E where A.date between '#{from_date}' and '#{to_date}' and A.entity_code='#{entity_code}' and E.emp_code=A.employee_code and A.cc_code in (#{cc_ids}) and A.location_code in (#{l_ids}) and A.sub_location_code in (#{sl_ids}) group by A.employee_code,E.status,A.employee_name,A.cc_code,A.cc_name,A.location_code, A.location_name,A.sub_location_code,sub_location_name SQL end this is the sql query wre im showing the data in the grid, now i need to add one custom export for that i need from-date and to-date as per me im getting only emp_code,name,cc_code,name,location_code,name,sublocation_code,name.. now i need to be get Present-Shifts Present-Days Absent-Days Leave-Days C/Off-Days W/Off-Days also from-date n to-date like may-1st, may-2nd....may31st as per the month attendance.rb def self.to_csv attributes = %w{ Employee-Code Employee-Name Location(Site)-Code Location(Site)-Name SubLocation-Code SubLocation-Name CostCenter-Code CostCenter-Name Status Present-Shifts Present-Days Absent-Days Leave-Days C/Off-Days W/Off-Days } CSV.generate(headers: true) do |csv| csv << attributes Attendance.all.each do |attendance| tump = {present_shifts: sum(case when attendance.status='Present' then 1 else 0 end), present_days: distinct(case when attendance.status='Present' then attendance.date end).count, absent_days: sum(case when attendance.status = 'Absent' then 1 else 0 end), leave_days: sum(case when attendance.status = 'Leave' then 1 else 0 end), cutoff_days: sum(case when attendance.status='C Off' then 1 else 0 end), weekoff_days: sum(case when attendance.status='W Off' then 1 else 0 end) } csv << [attendance.employee_code, attendance.employee_name, attendance.location_code, attendance.location_name, attendance.sub_location_code, attendance.sub_location_name, attendance.cc_code, attendance.cc_name, attendance.status, tump[:present_shifts], tump[:present_days], tump[:absent_days], tump[:leave_days], tump[:cutoff_days], tump[:weekoff_days] attendance.to_date end end end end can any one suggest me how to export the sheet with that columns csv format.. since i tried to get but as per my query im getting correct data in index as it is need to be get export sheet.... |
search function for conversations in ruby on rails Posted: 24 May 2016 06:36 AM PDT I m new to rails. I would like to add a search function for my rails app. the user can search for the conversations that he made with other users. in that search, he can type keywords of the messages or the user name that he chatted. Can some one guide me through this... conversation.rb is, class Conversation < ActiveRecord::Base belongs_to :sender, foreign_key: :sender_id, class_name: 'User' belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User' has_many :messages, dependent: :destroy validates_uniqueness_of :sender_id, scope: :recipient_id scope :involving, -> (user) do where("conversations.sender_id = ? OR conversations.recipient_id = ?", user.id, user.id) end scope :between, -> (sender_id, recipient_id) do where("(conversations.sender_id = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)", sender_id, recipient_id, recipient_id, sender_id) end end message.rb is, class Message < ActiveRecord::Base belongs_to :conversation belongs_to :user validates_presence_of :content, :conversation_id, :user_id def message_time created_at.strftime("%v") end end conversations_controller.rb is, class ConversationsController < ApplicationController before_action :authenticate_user! def index @users = User.all @conversations = Conversation.involving(current_user) end def create if Conversation.between(params[:sender_id], params[:recipient_id]).present? @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first else @conversation = Conversation.create(conversation_params) end redirect_to conversation_messages_path(@conversation) end private def conversation_params params.permit(:sender_id, :recipient_id) end end messages_controller.rb is, class MessagesController < ApplicationController before_action :authenticate_user! before_action :set_conversation def index if current_user == @conversation.sender || current_user == @conversation.recipient @other = current_user == @conversation.sender ? @conversation.recipient : @conversation.sender @messages = @conversation.messages.order("created_at DESC") else redirect_to conversations_path, alert: "You don't have permission to view this." end end def create @message = @conversation.messages.new(message_params) @messages = @conversation.messages.order("created_at DESC") if @message.save respond_to do |format| format.js end end end private def set_conversation @conversation = Conversation.find(params[:conversation_id]) end def message_params params.require(:message).permit(:content, :user_id) end end Can someone guide me to write the functionality for search and view the results of the search. i have tried in two different types but not worked. Thanks in advance |
Enterprise has_many :user devise [on hold] Posted: 24 May 2016 06:32 AM PDT I have a problem, devise have implemented for users. Also I have a table called companies. It turns out that a company can have many users and need the admin can create respective users of the company in its panel. By the way, pundit use. PD: Create an intermediate table to assign users and companies. |
Rails quickly find record where has_many associations exactly match array of association ids Posted: 24 May 2016 06:27 AM PDT I've got a Product model which has_many OptionValue records, which describe color , size , etc. Within my code, I need to query the Product model where the product.option_values.pluck(:id) array exactly matches an array of (e.g.) options = [1, 6, 4] . Running something like Product.includes(:option_values).where(option_values: { id: options_array }) returns all values that match at least one element of the options array, rather than all of them. I've developed an inefficient way of getting the record I need, as follows: Product.all.each { |v| return v if v.option_values.pluck(:id).sort == options_array.sort } Obviously the above is way ott and I'm sure there's a simpler way to handle this, and I'm happy to use ActiveRecord or a straight SQL query (though I'm not too hot on the latter, so haven't come up with anything yet). Any advice on the best way of achieving this greatly appreciated. Not sure I've explained this perfectly, so please comment if you've any questions. Thanks in advance, Steve. |
Pass params using button_to or button_tag Posted: 24 May 2016 07:12 AM PDT Im currently working on a ruby on rails app and im having a problem regarding passing parameters using button_to or button_tag The scenario is i can't pass the parameter using button_tag or when using button_to i can't go to my controller it says "AuthenticityToken" is there any way or proper way on passing parameter to a controller using button?. <%= button_tag "Update", :type => 'button', :class => "btn btn-info", :onclick => "location.href = 'student/displayStudent'" , params: {id: student.student_name}%> thanks. |
Form routes to the wrong action causing errors Posted: 24 May 2016 05:57 AM PDT I created an itinerary web app that allows a user to upload itineraries and 'download' other users itineraries into their profile. For whatever reason instead of my download button routing to the downloads controller, it routes to the itineraries controller and breaks my app. I can't seem to figure out why - hope you can help. Here's the download button on the itinerary show page: Itineraries/show.html.erb <% if logged_in? %> <% unless current_user.downloaded?(@itinerary) %> <%= render 'download' %> <% end %> <% else %> <p> You need to be logged in to download this. </p> <% end %> The partial rendered should route to the download controller: itineraries/_download.html.erb <%= form_for(current_user.downloadeds.build) do |f| %> <div><%= hidden_field_tag :downloaded_id, @itinerary.id %></div> <%= f.submit "Download", class: "btn btn-primary" %> <% end %> Class DownloadsController < ApplicationController before_action :logged_in_user def create #download id is established in the download form @itinerary = Itinerary.find(params[:downloaded_id]) current_user.download(@itinerary) redirect_to @itinerary end Instead it routes to the itineraries controller and this returns the following error - ActionController error - param is missing or value is empty: itinerary itineraries_controller.erb def create @itinerary = current_user.itineraries.build(itinerary_params) #@user = User.find(params[:id]) if @itinerary.save # render the page with the users itineraries flash[:success] = "Your itinerary has been added!" redirect_to request.referrer || current_user else #show the add itinerary page flash[:error] = @itinerary.errors.full_messages render 'new' end end Lastly here are my routes: routes # You can have the root of your site routed with "root" root 'static_pages#home' get 'signup' => 'users#new' get 'help' => 'static_pages#help' get 'about' => 'static_pages#about' get 'login' => 'sessions#new' post 'login' => 'sessions#create' delete 'logout' => 'sessions#destroy' resources :users resources :itineraries do resources :reviews end resources :downloads, only: [:create, :show] mount PdfjsViewer::Rails::Engine => "/pdfjs", as: 'pdfjs' |
Ruby on Rails validate a number [on hold] Posted: 24 May 2016 06:13 AM PDT What is the best way to validate a answer input by a user, validation rules below: Examples of formats allowed 1, 2, 3, 4...to 12 The value is 2 answers for 12 choices model: class Questions < ApplicationRecord belongs_to :user validates :user, presence: true validates :answers, presence: true end Html: <h3>question</h3> <% (1..12).each do |x| %> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-danger btn-circle"> <input type="checkbox" name="questions[answer][]" id="optionsCheckbox<%= x %>" value="<%= x %>" /> <%= x %> </label> </div> <% end %> </ul> <%= f.button :submit, "submit", class: "btn btn-success" %> in controller: private def question_params params.require(:question).permit(answer: []) end answer is a string in questions table |
Add a reference column using migration having non standard primary key column Posted: 24 May 2016 06:23 AM PDT I have a model which has a non-rails conventional primary key. class Guoid < ActiveRecord::Base self.primary_key = :guoid end and related migration class CreateGuoids < ActiveRecord::Migration def change create_table :guoids, id: false do |t| t.integer :guoid, limit: 8, auto_increment: true, primary_key: true t.integer :parent_guoid, limit: 8 t.string :resource_type, limit: 60 end end end Now I want to reference this model in another model and trying to create migration using references which doesn't to work. class ContentUnit < ActiveRecord::Base self.primary_key = :guoid end class Content < ActiveRecord::Base self.primary_key = :guoid belongs_to :user belongs_to :content_unit end and related migration class CreateContents < ActiveRecord::Migration def change create_table :contents, id: false do |t| t.references :content_unit, index: true, foreign_key: true t.references :user, index: true, foreign_key: true end end end When I run the migration, I am getting following error. Mysql2::Error: Can't create table `myapp_development_cr1`.`#sql-54a_308` (errno: 150 "Foreign key constraint is incorrectly formed"): ALTER TABLE `contents` ADD CONSTRAINT `fk_rails_823443bd0d` FOREIGN KEY (`content_unit_id`) REFERENCES `content_units` (`id`) I am expecting to create content_unit_guoid foreign key in contents table referencing guoid in guoids table. I used activerecord-mysql-awesome gem to work well with non-rails convention primary keys. Here is a trigger which first creates a record in guids table and use it's pk as pk of the target table. DELIMITER $$ CREATE TRIGGER `content_before_insert` BEFORE INSERT ON `content` FOR EACH ROW BEGIN IF NEW.guoid = 0 THEN INSERT INTO `content`.guoids (resource_type) VALUES('Content'); SET NEW.guoid = LAST_INSERT_ID(); END IF; END $$ DELIMITER ; |
ActiveModel::ForbiddenAttributesError in Admin::MerchantsController#create Posted: 24 May 2016 05:27 AM PDT I am getting ForbiddenAttrutesError every time I try and save the below form .mdl-grid.mdl-cell.mdl-cell--6-col.mdl-cell--4-offset .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = form.text_field :name, class: 'mdl-textfield__input' = form.label :name, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = form.email_field :email, class: 'mdl-textfield__input' = form.label :email, class: 'mdl-textfield__label' = form.fields_for :addresses, Address.new do |address_fields| .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :first_name, class: 'mdl-textfield__input' = address_fields.label :first_name, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :last_name, class: 'mdl-textfield__input' = address_fields.label :last_name, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :address1, class: 'mdl-textfield__input' = address_fields.label :address1, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :address2, class: 'mdl-textfield__input' = address_fields.label :address2, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :city, class: 'mdl-textfield__input' = address_fields.label :city, class: 'mdl-textfield__label' .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label = address_fields.text_field :zip_code, class: 'mdl-textfield__input' = address_fields.label :zip_code, class: 'mdl-textfield__label' Address Model class Address < ActiveRecord::Base belongs_to :state belongs_to :country belongs_to :address_type belongs_to :addressable, :polymorphic => true Merchant Model has_many :addresses, dependent: :destroy, as: :addressable has_one :default_billing_address, -> { where(billing_default: true, active: true) }, as: :addressable, class_name: 'Address' has_many :billing_addresses, -> { where(active: true) }, as: :addressable, class_name: 'Address' has_one :default_shipping_address, -> { where(default: true, active: true) }, as: :addressable, class_name: 'Address' has_many :shipping_addresses, -> { where(active: true) }, as: :addressable, class_name: 'Address' before_validation :sanitize_data validates :name, presence: true, length: { maximum: 255 } validates :email, format: { with: CustomValidators::Emails.email_validator }, :length => { :maximum => 255 } # geocoded_by :address # after_validation :geocode # after_create :sanitize_dates accepts_nested_attributes_for :addresses Merchant Controller private def allowed_params params.require(:merchant).permit(:name, :email, addresses_attributes: [:first_name, :last_name, :address1, :address2, :city, :zip_code, :country_id]) end Full Error Message Started POST "/en/admin/merchants" for 127.0.0.1 at 2016-05-24 22:30:02 +1000 Processing by Admin::MerchantsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "merchant"=>{"name"=>"Test", "email"=>"test@test.com", "addresses_attributes"=>{"0"=>{"first_name"=>"Paul", "last_name"=>"M", "address1"=>"12 Dansu Ct", "address2"=>"", "city"=>"Hallam", "zip_code"=>"3803"}}}, "commit"=>"Create", "locale"=>"en"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["remember_token", "5d0fec3c9ccb5afcd28845dd83eb18869f66b4b0"]] Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.4ms) ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError): activemodel (4.2.6) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment' activerecord (4.2.6) lib/active_record/attribute_assignment.rb:33:in `assign_attributes' activerecord (4.2.6) lib/active_record/core.rb:566:in `init_attributes' activerecord (4.2.6) lib/active_record/core.rb:281:in `initialize' activerecord (4.2.6) lib/active_record/inheritance.rb:61:in `new' activerecord (4.2.6) lib/active_record/inheritance.rb:61:in `new' cancancan (1.14.0) lib/cancan/controller_resource.rb:80:in `build_resource' cancancan (1.14.0) lib/cancan/controller_resource.rb:61:in `load_resource_instance' cancancan (1.14.0) lib/cancan/controller_resource.rb:32:in `load_resource' cancancan (1.14.0) lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource' cancancan (1.14.0) lib/cancan/controller_resource.rb:10:in `block in add_before_filter' activesupport (4.2.6) lib/active_support/callbacks.rb:448:in `instance_exec' activesupport (4.2.6) lib/active_support/callbacks.rb:448:in `block in make_lambda' activesupport (4.2.6) lib/active_support/callbacks.rb:164:in `block in halting' activesupport (4.2.6) lib/active_support/callbacks.rb:504:in `block in call' activesupport (4.2.6) lib/active_support/callbacks.rb:504:in `each' activesupport (4.2.6) lib/active_support/callbacks.rb:504:in `call' activesupport (4.2.6) lib/active_support/callbacks.rb:92:in `__run_callbacks__' activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks' activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument' actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (4.2.6) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (4.2.6) lib/abstract_controller/base.rb:137:in `process' actionview (4.2.6) lib/action_view/rendering.rb:30:in `process' actionpack (4.2.6) lib/action_controller/metal.rb:196:in `dispatch' actionpack (4.2.6) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' actionpack (4.2.6) lib/action_controller/metal.rb:237:in `block in action' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:74:in `dispatch' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:43:in `serve' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `each' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call' bullet (5.1.0) lib/bullet/rack.rb:10:in `call' clearance (1.14.1) lib/clearance/rack_session.rb:23:in `call' rack (1.6.4) lib/rack/etag.rb:24:in `call' rack (1.6.4) lib/rack/conditionalget.rb:38:in `call' rack (1.6.4) lib/rack/head.rb:13:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call' rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call' activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call' activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__' activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks' activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app' web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call' web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch' web-console (3.1.1) lib/web_console/middleware.rb:18:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app' railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged' railties (4.2.6) lib/rails/rack/logger.rb:20:in `call' quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets' actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' rack (1.6.4) lib/rack/runtime.rb:18:in `call' rack (1.6.4) lib/rack/lock.rb:17:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call' rack (1.6.4) lib/rack/sendfile.rb:113:in `call' railties (4.2.6) lib/rails/engine.rb:518:in `call' railties (4.2.6) lib/rails/application.rb:165:in `call' rack (1.6.4) lib/rack/content_length.rb:15:in `call' puma (3.4.0) lib/puma/configuration.rb:224:in `call' puma (3.4.0) lib/puma/server.rb:569:in `handle_request' puma (3.4.0) lib/puma/server.rb:406:in `process_client' puma (3.4.0) lib/puma/server.rb:271:in `block in run' puma (3.4.0) lib/puma/thread_pool.rb:114:in `block in spawn_thread' |
How to pre populate current password while changing password through devise Posted: 24 May 2016 05:12 AM PDT Hello I have given following view file <div class="panel-body"> <%= form_for @user, :url =>update_change_password_user_path(spree_current_user.id), :method => :put do |f| %> <p> <%= f.password_field :current_password, class: "form-control"%> </p> <p> <%= f.label :password, Spree.t(:new_password) %><br /> <%= f.password_field :password, :class => "form-control" %><br /> </p> <p> <%= f.label :password_confirmation, Spree.t(:confirm_password) %><br /> <%= f.password_field :password_confirmation, :class => "form-control" %><br /> </p> <%= f.submit Spree.t(:update), :class => 'btn btn-lg btn-success btn-block' %> <% end %> </div> My requirement is to get current_password field pre filled please guide me hot to fetch current_password of user. I am using gem 'spree_auth_devise', '~> 3.0.0' |
Get a file name from ActionDispatch Posted: 24 May 2016 05:04 AM PDT I have this path coming in my terminal but I am unable to fetch the filename .
{"profile"=>#<ActionDispatch::Http::UploadedFile:0x0000000371fe28 @tempfile=#<Tempfile:/tmp/RackMultipart20160524-10164-1tytgpj.png>, @original_filename="abcas.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"user[profile]\"; filename=\"abcas.png\"\r\nContent-Type: image/png\r\n">} I am trying **puts "dddd#{ params[:user][:profile].original_filename}"** but getting this error undefined method `[]' for nil:NilClass I have look at this link but wasn't helpful |
jQuery SVG Element Mouse Event Posted: 24 May 2016 05:00 AM PDT Been scratching my head for the past hour trying to figure this out. I have the following SVG inline code and I can't seem to trigger a mouseenter event on a group or even a polygon element. What am I missing guys? HTML <g id="hall1" class="hallBlock"> <polygon id="Fill-1" fill="#FFFFFF" points="0.508 83.586 83.957 83.586 83.957 0.501 0.508 0.501"></polygon> <polygon id="Stroke-2" stroke="#F5F5F5" points="0.508 83.586 83.957 83.586 83.957 0.501 0.508 0.501"></polygon> <text id="01" font-family="LucidaGrande, Lucida Grande" font-size="18" font-weight="normal" fill="#D6D6D6"> <tspan x="32.9956" y="43.7445813">01</tspan> </text> </g> jQuery var $hallBlock = $('.hallBlock'); $hallBlock.mouseenter(function(){ console.log('mouse enter'); }); |
weird error in production server on digital ocean Posted: 24 May 2016 05:39 AM PDT I have the devise gem to enable authorisation and authentication of admin users to my web app. However once i try to access blog.xxxx.com/admins/sign_up i get an application error. Below are the contents of my production.log file I, [2016-05-24T06:30:33.215786 #21746] INFO -- : Started GET "/blog/xmlrpc.php" for 89.248.174.4 at 2016-05-24 06:30:33 -0400 F, [2016-05-24T06:30:33.220309 #21746] FATAL -- : ActionController::RoutingError (No route matches [GET] "/blog/xmlrpc.php"): actionpack (4.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' actionpack (4.2.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.2.2) lib/rails/rack/logger.rb:38:in `call_app' railties (4.2.2) lib/rails/rack/logger.rb:20:in `block in call' activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `block in tagged' activesupport (4.2.2) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `tagged' railties (4.2.2) lib/rails/rack/logger.rb:20:in `call' actionpack (4.2.2) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' rack (1.6.4) lib/rack/runtime.rb:18:in `call' activesupport (4.2.2) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' rack (1.6.4) lib/rack/sendfile.rb:113:in `call' railties (4.2.2) lib/rails/engine.rb:518:in `call' railties (4.2.2) lib/rails/application.rb:164:in `call' puma (3.4.0) lib/puma/configuration.rb:224:in `call' puma (3.4.0) lib/puma/server.rb:569:in `handle_request' puma (3.4.0) lib/puma/server.rb:406:in `process_client' puma (3.4.0) lib/puma/server.rb:271:in `block in run' puma (3.4.0) lib/puma/thread_pool.rb:114:in `call' puma (3.4.0) lib/puma/thread_pool.rb:114:in `block in spawn_thread' |
pass javascript variable to ruby on rails controller to send in api further Posted: 24 May 2016 04:58 AM PDT I am having a google api map as index.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script> // Note: This example requires that you consent to location sharing when // prompted by your browser. If you see the error "The Geolocation service // failed.", it means you probably did not give permission for the browser to // locate you. function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 15 }); var infoWindow = new google.maps.InfoWindow({map: map}); // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infoWindow.setPosition(pos); infoWindow.setContent('Location found.'); map.setCenter(pos); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); } } function handleLocationError(browserHasGeolocation, infoWindow, pos) { infoWindow.setPosition(pos); infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.'); } </script> <script async defer src="https://maps.googleapis.com/maps/api /js?key=AIzaSyBNvjq57_K8vPYRKETMN6bDogqCpRvBoA0&callback=initMap"> </script> </body> </html> I want to use the var=pos in ruby on rails controller i.e products controller require 'rubygems' require 'httparty' class ProductsController < ApplicationController def index @results = HTTParty.get("https://api.uber.com /v1/products?server_token=xyz&latitude=37.7759792&longitude=-122.41823").parsed_response respond_to do |format| format.json { render :json => JSON.parse(@results) } format.html { render "index.html.erb" } end end end and then pass seperate latitude and longitude in the api url so that it can take any latitude and longitude instead of giving it manually. How can I do it ? Any suggestion would be appreciated. |
Rails Octopus Gem - Log which database queried Posted: 24 May 2016 04:08 AM PDT Does anyone have a way to check which database is being queried from ActiveRecord using Octopus Gem? I want to check whether the read requests are actually hitting slave database and not master database. |
Ruby Net::SSH infinity wait for password Posted: 24 May 2016 04:09 AM PDT I have a simple functional for run some command via ssh, here is an example: ... Net::SSH.start( self.host, self.user, config: true, keys: [self.pem_key] ) do| ssh | result = ssh.exec! self.command ... It works OK except case when I forgot configure remote host (as example add key in ~/.ssh/authorized) and my app stuck on password request: Completed 200 OK in 246ms (Views: 238.1ms | ActiveRecord: 4.3ms) Started POST "/xxx" for ::1 at 2016-05-24 13:43:11 +0300 Processing by XXX::XXXController#run_now as JS Parameters: {"id"=>"2"} XXX::Check Load (0.3ms) SELECT ... (0.1ms) BEGIN SQL (0.3ms) UPDATE ... (0.3ms) COMMIT Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text. some_user@some_host's password: How I can set timeout for this case or how I can exclude this case at all (raise some error?) |
rails has_many :through association doesnt work Posted: 24 May 2016 04:35 AM PDT I have a problem with a has_many through association. I have an account model which has many offices and hotels account.rb : class Account < ActiveRecord::Base # associations has_many :partnerships, through: :hotels, dependent: :destroy has_many :partnerships, through: :offices, dependent: :destroy has_many :users, through: :hotels, dependent: :destroy has_many :hotels, dependent: :destroy has_many :offices, dependent: :destroy belongs_to :admin, class_name: "User", foreign_key: "admin_user_id", dependent: :destroy then I have a partnerships table which is a join table between hotels and offices thus both hotel and office have many partnerships: class Hotel < ActiveRecord::Base has_many :partnerships belongs_to :account has_and_belongs_to_many :user class Office < ActiveRecord::Base belongs_to :account has_and_belongs_to_many :users has_many :partnerships and finally my partnership model : class Partnership < ActiveRecord::Base belongs_to :hotel belongs_to :office Yet when I test the association between account and partnership with an account that has hotels with partnerships (@account.partnerships ), I get an empty [], whereas when I directly use the relevant hotel(@hotel.partnerships ), I get my list of relevant partnerships. Could you tell me why these associations dont work : has_many :partnerships, through: :hotels, dependent: :destroy has_many :partnerships, through: :offices, dependent: :destroy |
Load UI in batches Posted: 24 May 2016 03:53 AM PDT I have a long FORM that has lots of fields(as fields can be dynamically created and I can't restrict the number of fields). When I edit form that has less than 20 fields, then the form loads properly. But, it starts getting delayed as the number of fields keeps increasing. I tried the following to batch load the FORM: #Inside edit.html.haml :javascript load_next_questions_set("#{url}", "#{params}", #{total_pages}, #{current_page}); #Inside app.js function load_next_questions_set(url, params, total_pages, current_page) { if(current_page <= total_pages) { var next_page = current_page + 1; jQuery.ajax({ url: url data: params, success: function(data) { jQuery("#some_div").append(data); setTimeout(function() { load_next_questions_set( jQuery.extend({url: url, total_pages: total_pages, current_page: current_page}, params) ); }, 2000); } }); } } My moto is to load the form in the background without the knowledge of user. The problem is, until the entire form is loaded, the page becomes sluggish. How can I optimize this? And How can I avoid memory leaks? (if any). Or is there any better way to achieve this in Rails level? |
search parameters mongodb wildcard Posted: 24 May 2016 03:48 AM PDT i'm newbie in mongodb , i want to use wilcard for search , it works for me but when i add . before * for example => reference:ti-sungl.* i want to use directly for search reference:ti-sungl* without point this is the code if params[:query].present? if params[:query].is_a? String query_array = params[:query].split(/:/) if query_array.length == 3 field_name = escape_seach_query(query_array[0]) + '.' + escape_seach_query(query_array[1]) s.filter :term, field_name => escape_seach_query(query_array[2]) elsif query_array.length == 2 if (query_array[1] =~ /\*/) s.filter :regexp, escape_seach_query(query_array[0]) => escape_seach_query(query_array[1]) else s.filter :term, escape_seach_query(query_array[0]) => escape_seach_query(query_array[1]) end else s.query do |s| s.string escape_seach_query(params[:query]) end end else s.query do |s| s.string escape_seach_query(params[:query]) end end end |
How to access the parameter being validated Posted: 24 May 2016 05:15 AM PDT In the following example, is there a way to retrieve the name of the parameter being currently validated inside the if proc ? class MyModel < ActiveRecord::Base with_options if: proc{|o| "how to retreive the parameter being validated here?"} do validates :param_1, presence: true validates :param_2, presence: true end end I would like to avoid this kind of solution: class MyModel < ActiveRecord::Base validates :param_1, presence: true, if: proc{|o| o.need_validation?(:param_1)} validates :param_2, presence: true, if: proc{|o| o.need_validation?(:param_2)} end |
How and where to proceed Telegram message info? Posted: 24 May 2016 03:21 AM PDT I try to add Telegram bot to my project. And need to proceed incoming json when user send /start or /end command to my bot. lib/modules/telegram_bot.rb require 'telegram/bot' token = '_____' Telegram::Bot::Client.run(token) do |bot| bot.listen do |message| case message.text when '/start' if message.from.username user = UserProfile.find_by_telegram_id(message.username).user if user bot.api.send_message(chat_id: message.chat.id, text: "") user.user_profile.update_attribute(:telegram_notify, true) else bot.api.send_message(chat_id: message.chat.id, text: "") end else bot.api.send_message(chat_id: message.chat.id, text: "") end when '/end' bot.api.send_message(chat_id: message.chat.id, text: "") if message.from.username profile = UserProfile.find_by_telegram_id(message.username) if profile profile.update_attribute(:telegram_notify, false) bot.api.send_message(chat_id: message.chat.id, text: "") end else bot.api.send_message(chat_id: message.chat.id, text: "") end else bot.api.send_message(chat_id: message.chat.id, text: "") end end end I need to find user in my DB by his telegram username and proceed depend on result. But sure I'm doing wrong, because there is an error: uninitialized constant UserProfile (NameError) when I start ruby lib/modules/telegram_bot.rb . |
Compare multi-dimensional arrays Posted: 24 May 2016 03:31 AM PDT In a spec I want to compare two multi-dimensional arrays: array1 = [["a"],["b"],["c"]] array2 = [["b"]] expect(array1).to include(array2) But it returns: Failure/Error: expect(array1).to include(array2) expected [["a"], ["b"], ["c"]] to include [["b"]] Also this results in the same error: array1 = [["a"],["b"],["c"]] array2 = array1 expect(array1).to include(array2) So how can I compare these two arrays? |
Rails model - change true to yes Posted: 24 May 2016 05:49 AM PDT My model contains some boolean columns which return true or false. e.g. is_value has either a 1 or a 0. MyModel.all Is there a way of converting the is_value in the above line of code, or through a scope, such that true and false are converted to yes/no? It is possible when calling a model? |
Validate and fetch the overlapped record in rails model Posted: 24 May 2016 03:54 AM PDT I am using validates_overlap gem Using this gem I am not able to fetch that records .. because my req have to show in UI which one is overlapping. Please Suggest me how i can go forward. |
Capistrano and Rails deployment, unable to access bitbucket repo from ubuntu server Posted: 24 May 2016 05:06 AM PDT I have an Ubuntu server which can successfully deploy a Rails project to. I have created a new project, and would like to deploy this to the same server. But i am having a problem with accessing the bitbucket repo the code is stored on during the Capistrano deployment. DEBUG [60fbbd0f] Command: /usr/bin/env chmod +x /tmp/<project_name>/git-ssh.sh INFO [60fbbd0f] Finished in 0.098 seconds with exit status 0 (successful). INFO [b7870f98] Running /usr/bin/env git ls-remote --heads git@bitbucket.org:rmac/<project_name>.git as www-data@88.xxx.xxx.xxx DEBUG [b7870f98] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/<project_name>/git-ssh.sh /usr/bin/env git ls-remote --heads git@bitbucket.org:rmac/<project_name>.git ) DEBUG [b7870f98] conq: repository does not exist. DEBUG [b7870f98] fatal: Could not read from remote repository. DEBUG [b7870f98] DEBUG [b7870f98] Please make sure you have the correct access rights DEBUG [b7870f98] and the repository exists. I have tried this SSHKit::Runner::ExecuteError and other answers but to no avail. I have checked my server processes and ssh agent is running. I find it difficult to understand seeing as my other project deploys to the server no problems. I am using the same machine, the same deployment keys, the same bitbucket account. Any ideas? Thanks |
ruby on rails: Uncaught Error: Syntax error, unrecognized expression Posted: 24 May 2016 02:47 AM PDT i'm getting Uncaught Error: Syntax error, unrecognized expression: jquery.self-c64a743….js?body=1:1503 everytime I open a edit form for a post, via ajax, I don't know why i'm getting this, this was working well previously. I'm using trix gem to use WYSIWYG text area, I don't know if its related to that. here is my edit.js.erb: $('.improv_desc_<%= @improvement_action.id %>').empty(); $('.improv_desc_<%= @improvement_action.id %>').append("<%= escape_javascript(render partial: 'improvement_actions/edit') %>"); $('.close_edit_<%= @improvement_action.id %>').click(function(){ $('.improv_desc_<%= @improvement_action.id %>').empty().append('<%= raw @improvement_action.description %>'); }); $('.edit_btn').click(function(){ // ao clicar noutro "edit" fechar o que estava a ser editado if($('.improv_desc_<%= @improvement_action.id %>').hasClass('edit')) { // se a improv tiver a class edit (adicionada depois de fazer update) entao é porque foi editada e nao está o edit form aberto } else if($(this).attr("id") != 'edit_btn_<%= @improvement_action.id %>'){ // se o botao de edit nao for o que estava a editar, ele fecha o edit que estava a fazer e abre o clicado $('.edit_form_<%= @improvement_action.id %>').remove(); $('.improv_desc_<%= @improvement_action.id %>').empty().append('<%= raw @improvement_action.description %>'); } }); $('.improv_desc_<%= @improvement_action.id %>').removeClass('edit'); And my edit partial: <%= stylesheet_link_tag "improvement_actions" %> <%= form_for [@performance_indicator, @improvement_action] , remote: true do |f| %> <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css"> <div class="row edit_form_<%= @improvement_action.id %> edit_imprv" > <div class="col-md-6 editcss"> <span class="glyphicon glyphicon-remove close_button pull-right close_edit_<%= @improvement_action.id %>" title="Close edit form"></span> <div class="widget-area no-padding blank"> <div class="status-upload"> <form> <%= f.trix_editor :description, placeholder: "Recommend an improvement action (one per post)", :class => "textarea"%> <%= submit_tag "Edit Recommendation", :class => "btn btn-primary button btn_post" %> </form> </div><!-- Status Upload --> </div><!-- Widget Area --> </div> </div> <%end%> Here are my errors: |
NoMethodError: undefined method Posted: 24 May 2016 03:49 AM PDT I am working through Agile Web Development with ruby on rails. While running a test, I get the following: Error: LineItemsControllerTest#test_should_update_line_item: NoMethodError: undefined method 'product_id' for nil:NilClass test/controllers/line_items_controller_test.rb:13:in `block in <class:LineItemsControllerTest> Here is my test file require 'test_helper' class LineItemsControllerTest < ActionController::TestCase test "should create line_item" do assert_difference('LineItem.count') do post :create, product_id: products(:ruby).id end assert_redirected_to cart_path(assigns(:line_item).cart) end test "should update line_item" do patch :update, id: @line_item, line_item: { product_id: @line_item.product_id } assert_redirected_to line_item_path(assigns(:line_item)) end end Could someone kindly explain why I get a NoMethodError: undefined method while the book says it should be fine? Thank you! Update 1 As per Boltz0r's comment below, here are my create and update methods. I tried comparing what I have versus what is in the book and can't seem to find the problem. def create product = Product.find(params[:product_id]) @line_item = @cart.add_product(product.id) respond_to do |format| if @line_item.save format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' } format.json { render :show, status: :created, location: @line_item } else format.html { render :new } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @line_item.update(line_item_params) format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' } format.json { render :show, status: :ok, location: @line_item } else format.html { render :edit } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end |
Ability for users to add images to comments in Rails forum Posted: 24 May 2016 03:27 AM PDT So i have added the ability for users to add images to posts in my rails forum. I now want users to be able to add images to comments to posts. I began with a migration add_attachment_image_to_comments.rb class AddAttachmentImageToComments < ActiveRecord::Migration def self.up change_table :comments do |t| t.attachment :image end end def self.down remove_attachment :comments, :image end end Edited the view file: = simple_form_for([@post, @post.comments.build]) do |f| = f.input :comment = f.input :image %br = f.submit Here is the posts_controller file: class PostsController < ApplicationController before_action :find_post, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] def index @posts = Post.all.order("created_at DESC").paginate(page: params[:page], per_page: 7) end def show end def new @post = current_user.posts.build end def create @post = current_user.posts.build(post_params) if @post.save redirect_to @post else render 'new' end end def edit end def update if @post.update(post_params) redirect_to @post else render 'edit' end end def destroy @post.destroy redirect_to root_path end private def find_post @post = Post.find(params[:id]) end def post_params params.require(:post).permit(:title, :content, :image) end end Here is the comments_controller file: class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment].permit(:comment, :image)) @comment.user_id = current_user.id if current_user @comment.save if @comment.save redirect_to post_path(@post) else render 'new' end end def edit @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) if @comment.update(params[:comment].permit(:comment, :image)) redirect_to post_path(@post) else render 'edit' end end def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy redirect_to post_path(@post) end end This give users the ability to add the attachment. The problem i have now is getting the image to show in the comments section on the post. This is my show file: #post_content %h1= @post.title %p= @post.content = image_tag @post.image.url(:medium) #comments %h2 = @post.comments.count Comment(s) = render @post.comments = image_tag @comment.image.url(:medium) I get the error - undefined method `image' for nil:NilClass. Highlighing this row - = image_tag @comment.image.url(:medium) Any help much appreciated. |
rspec rails testing session_id Posted: 24 May 2016 03:35 AM PDT I have a quite peculiar thing to test. Recently we have changed from cookie-storage to active-record-storage when it comes to storing session information. This was done in order to prevent using session_id from cookies to continue browsing session even after users was logged out (That's a thing you need to sadly accept when using cookie-storage). Now I need to write some code to test whether moving to active-record-storage indeed fixed that security issue but I dont know how. The scenario is that: user signs in to the app users signs out of the app session_id from the request header is then used in get request to view a part of the app that normally needs authentication this should not be possible, because we are not authenticated(although we use the session_id from the previous request) we get a 401, or 404 or anything else than 200 hopefully. So far I have managed to get the session_id from the request -> @request.env["rack.sesion.options"][:id] but I don't know how to use and put this session_id into next request any ideas? |
Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
ReplyDeleteruby on rails training
ruby on rails training India
ruby on rails training Hyderabad