Update Nested Attributes Posted: 27 Dec 2016 07:38 AM PST I have a form with nested attributes. It all works perfect for creating a new product and at the same time creating a consumption record for that product in a different table. The problem is when i want to edit the product.. It does a SQL UPDATE for the product object and SQL INSERT for the nested consumptions object. One product has many consumptions so how can i program this to find and update all the consumptions associated with this product. Form View <%= form_for(@new_product) do |f| %> <div class="container"> <div class="name-category"> <h1>New Product</h1> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :price %><br> <%= f.number_field :price %> </div> <div class="field"> <%= f.select :category_id, Category.all.collect { |c| [ c.name, c.id ] } %> </div> </div> <div class="add-ingredients"> <div class="add-button"> <p id="more">Add Ingredients</p> </div> <%= f.fields_for :consumptions, @consumptions do |ff| %> <div id="new-ingredients-container"> <div class="titles"> <p>Ingrediente</p> <p>Consumo</p> </div> <div class="ingredients-row"> <%= ff.select :supply_id, Supply.all.collect { |c| [ c.name, c.id ] }, {}, {class: "ingredients-select"} %> <%= ff.number_field :consumption %> </div> </div> <% end %> </div> </div> <div class="actions"> <%= f.submit %> </div> <% end %> Product Controller def new @new_product = Product.new @consumptions = @new_product.consumptions.build end def update @product = Product.find(params[:id]) @consumptions = @product.consumptions @consumptions.each do |c| c.update(params.permit(:consumption_id, :supply_id, :product_id, :consumption)) end respond_to do |format| if @product.update(product_params) format.html { redirect_to @product, notice: 'Product was successfully updated.' } format.json { render :show, status: :ok, location: @product } else format.html { render :edit } format.json { render json: @product.errors, status: :unprocessable_entity } end end end Thanks a lot! |
rails link_to on overlay div Posted: 27 Dec 2016 07:33 AM PST I have a div structured like so: <% @posts.each do |post| %> <!-- Shot --> <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"> <div class="shot shot-minimal"> <div class="shot-preview"> <a class="img" href="shot-gallery.html"><img src="http://rwdtow.stdout.in/img/avatar-icon.png" alt=""></a> <a class="text-overlay"> <span class="heading"><%= post.tite %></span> <span class="desc"><%= post.shortdescription %></span> <time datetime="2016-02-04 22:30">7 hours ago</time> </a> </div> <div class="shot-detail"> <div class="shot-info"> <p><%= post.title %></p> </div> <ul class="shot-stats"> <li><i class="fa fa-eye"></i><span>6.3k</span></li> <li><a class="like" href="#"><i class="fa fa-heart"></i><span>1.2k</span></a></li> </ul> </div> </div> </div> <!-- END Shot --> <% end %> In the above div i have an overlay: <a class="text-overlay"> <span class="heading"><%= post.tite %></span> <span class="desc"><%= post.shortdescription %></span> <time datetime="2016-02-04 22:30">7 hours ago</time> </a> So i placed a link_to with the overlay, so the text overlays, the text is clickable: <%= link_to post, class:"text-overlay" do %> <span class="heading"><%= post.tite %></span> <span class="desc"><%= post.shortdescription %></span> <time datetime="2016-02-04 22:30">7 hours ago</time> <% end %> The overlay works correct, but when i click on it, it does not take me to the show action for the post. Heres how my final code looks: <% @posts.each do |post| %> <!-- Shot --> <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"> <div class="shot shot-minimal"> <div class="shot-preview"> <a class="img" href="shot-gallery.html"><img src="http://rwdtow.stdout.in/img/avatar-icon.png" alt=""></a> <%= link_to post, class:"text-overlay" do %> <span class="heading"><%= post.tite %></span> <span class="desc"><%= post.shortdescription %></span> <time datetime="2016-02-04 22:30">7 hours ago</time> <% end %> </div> <div class="shot-detail"> <div class="shot-info"> <p><%= post.title %></p> </div> <ul class="shot-stats"> <li><i class="fa fa-eye"></i><span>6.3k</span></li> <li><a class="like" href="#"><i class="fa fa-heart"></i><span>1.2k</span></a></li> </ul> </div> </div> </div> <!-- END Shot --> <% end %> |
Rails association with a (non-activerecord) class (not a object/row) Posted: 27 Dec 2016 07:24 AM PST The problem: People may have many types of degrees (bachelor, master, phd, etc...). In my country, some degrees includes another. Ex.: Superior Degree may be either bachelor or licentiate. I'd like to create this structure in a class hierarchy: Bachelor < Superior < Degree Licentiate < Superior < Degree Master < Degree PHD < Degree Those classes don't need to have rows stored in the Database, but I'd like to associate them with some ActiveRecord objects of other classes. Should I just store classes name as strings? |
Ruby on Rails: can you store regex in a variable? [duplicate] Posted: 27 Dec 2016 07:16 AM PST This question already has an answer here: I check the format of my input against a custom regex. I use this regex in more than one place in my model, so I want to store it in a variable. MY_REGEX = '/\A*blablabla*\Z/' validates_format_of :my_input, :with => MY_REGEX, :allow_blank => true ... ... if somethingelse =~ MY_REGEX: # more code end Which yields: ArgumentError (A regular expression or a proc or lambda must be supplied as :with) Is this not allowed? |
savon gem SOAP-ERROR: Encoding: Violation of encoding rules Posted: 27 Dec 2016 07:09 AM PST I am using savon version-2 gem for soap requests, and for authorization and few other urls i didnt face problem, but for particular endpoint i need to search the date range from and to which needs to be passed inside item so the problem is first item get replaced by second how do i avoid this client = Savon.client(wsdl: "http://www.sss.ss/api/v2_soap/?wsdl", log_level: :debug, pretty_print_xml: true, log: true) session = client.call(:login, message: {username: 'sss', apiKey: 'sss'}) result = client.call(:sales_order_list, message: {sessionId: session.body[:login_response][:login_return], filters: {filter: {item: {key: 'created_at', value: {key: 'from', value: '2016-12-27 00:00:00'}}, item: {key: 'created_at', value: {key: 'to', value: '2016-12-27 23:59:59'}} }}}) the xml generated is like with the to value only and i get the error SOAP-ERROR: Encoding: Violation of encoding rules I think overwriting items is the problem How do i send 2 items inside filter |
Gettting Zero fee in Stripe Balance Transaction API Response Posted: 27 Dec 2016 07:04 AM PST I am using Stripe API for receiving the contribution from multiple user. So I want to generate statement for our customer so they can see what exact amount, fee deduction, transaction count etc. After looked into Stripe API I found there are two API(Stripe::Transfer and Stripe::BalanceTransaction ) these can be used to fullfil my requirement. So as per documentation Stripe API I am calling Stripe::Transfer API and this API returning correct response like below transfer = #<Stripe::Transfer:0x3f997455ac88 id=tr_1xxxxxxxxxxxxxx> JSON: { "id": "tr_1xxxxxxxxxxxxxxxxx", "object": "transfer", "amount": 9510, "amount_reversed": 0, "application_fee": null, "balance_transaction": "txn_123", "created": 1477485158, "currency": "usd", "date": 1477485158, "description": null, "destination": "acct_xxxxxxxxxxxxxx", "destination_payment": "py_xxxxxxxxxxx", "failure_code": null, "failure_message": null, "livemode": false, "metadata": {}, "method": "standard", "recipient": null, "reversals": {"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/transfers/tr_xx/reversals"}, "reversed": false, "source_transaction": "ch_xxxxxxxxx", "source_type": "card", "statement_descriptor": null, "status": "paid", "type": "stripe_account" } I am calling Stripe::BalanceTransaction API to get the details particular transfer's transactions balance_transaction_id = transfer.balance_transaction Stripe::BalanceTransaction.retrieve(balance_transaction_id) Getting below response #<Stripe::BalanceTransaction:0x3f9974f2f1c8 id=txn_123> JSON: { "id": "txn_123", "object": "balance_transaction", "amount": -9510, "available_on": 1478044800, "created": 1477485158, "currency": "usd", "description": null, "fee": 0, "fee_details": [ ], "net": -9510, "source": "tr_xxxxxxxx", "sourced_transfers": {"object":"list","data": [],"has_more":false,"total_count":0,"url":"/v1/transfers? source_transaction=tr_xxxx"}, "status": "available", "type": "transfer" } I setup application fee(2%) and this showing correct on Stripe Dashboard but in the above response I am getting fee is 0 So can anyone help/suggest me how can I get fee and total_count values in this response Thank you in Advance any kind of help and suggestion. |
How to get region in place of zipcode for UAE countries using google maps API? Posted: 27 Dec 2016 07:31 AM PST When I get results then in this i am not getting region of the selected UAE area because in UAE there is no postal code/zipcode. if any way to get region for UAE areas then suggest me. Below is my code: var componentForm = { street_number: 'short_name', route: 'long_name', administrative_area_level_1: 'short_name', locality: 'long_name', postal_code: 'short_name' }; var formComponentIds = { street_number: 'user_add_street', route: 'user_add_street', administrative_area_level_1: 'user_add_state', locality: 'user_add_city', postal_code: 'user_add_zipcode' }; function initAutocomplete () { autocomplete = new google.maps.places.Autocomplete((document.getElementById('user_add_street')),{types: ['geocode']}); autocomplete.addListener('place_changed', fillInAddress); $(document).on('focusout', '#pickupStreet', function() { var firstResult = $(".pac-container .pac-item:first").text(); var geocoder = new google.maps.Geocoder(); geocoder.geocode({"address":firstResult }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var lat = results[0].geometry.location.lat(), lng = results[0].geometry.location.lng(), placeName = results[0].address_components[0].long_name, latlng = new google.maps.LatLng(lat, lng); $('#pickup_latitude').val(lat); $('#pickup_longitude').val(lng); debugger for (var i = 0; i < results[0].address_components.length; i++) { if( results[0].address_components[i].types[0] == 'route'){ $('#pickupStreet').val(results[0].address_components[i-1].long_name + " " + results[0].address_components[i].long_name); } else if (results[0].address_components[i].types[0] == 'locality'){ $('#pickupCity').val(results[0].address_components[i].long_name); } else if (results[0].address_components[i].types[0] == 'administrative_area_level_1'){ $('#pickupState').val(results[0].address_components[i].long_name); } // else if (results[0].address_components[i].types[0] == 'postal_code'){ // $('#pickupZipcode').val(results[0].address_components[i].long_name); // } else{ console.log(); } } $('#user_customer_detail_attributes_zipcode').val($('#pickupZipcode').val()); } }); }); } function fillInAddress () { // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); $('#pickup_latitude').val(place.geometry.location.lat()); $('#pickup_longitude').val(place.geometry.location.lng()); if (place.address_components) { for (var component in componentForm) { componentId = formComponentIds[component]; document.getElementById(componentId).value = ''; document.getElementById(componentId).disabled = false; } // Get each component of the address from the place details // and fill the corresponding field on the form. for (var i = 0; i < place.address_components.length; i++) { var addressType = place.address_components[i].types[0]; if (componentForm[addressType]) { var val = place.address_components[i][componentForm[addressType]]; if (formComponentIds[addressType] == 'user_add_street') { var street = document.getElementById(formComponentIds[addressType]).value; document.getElementById(formComponentIds[addressType]).value = street + ' ' + val; } else { document.getElementById(formComponentIds[addressType]).value = val; } } } $('#user_add_street').val(place.name.split(',')); document.getElementById('user_add_apartment_number') = ''; } else { splitted_address = place.name.split(','); street = splitted_address[0]; city = splitted_address[1]; state = splitted_address[2]; $('#pickupStreet').val(street); $('#pickupCity').val(city); $('#pickupState').val(state); $('#pickupZipcode').val(''); } } |
RubyMine Terminal uses wrong RVM and no history in rails console Posted: 27 Dec 2016 06:26 AM PST After updating RubyMine I've got working environment with right Settings and rvm current returned 2.2.4 version as expected. But Rails was running always under another version (2.3.1 ). |
Dynamic concerns for a Rails model Posted: 27 Dec 2016 06:41 AM PST For a project I needed the ability to upload video's to a video server. At first the scope was to only upload to a Kaltura video server. To enable this, I created a simple concern that added some callback methods to the model which handle the uploads. These callback methods (specifically for Kaltura) are being loaded like so: class Videofile < ActiveRecord::Base include KalturaBox::Entry end And they contain basics like this (simplified version): module KalturaBox module Entry extend ActiveSupport::Concern included do before_save :create_kaltura_item, on: :create private def create_kaltura_item puts 'create callback called' self.upload end end end Now the scope has broadened, and I was asked to also include Vimeo uploads as an option. Is it possible to dynamically embed the concerns based on an attribute of the model, or should I consider using STI instead? I was thinking about creating a drop-down called "video_type". How do I include the correct code based on that attribute? |
Unable to split the statement into multiple lines from an array in Ruby Posted: 27 Dec 2016 07:21 AM PST I want to split the statement array into 2 different lines in RUBY: statement = ["Statement1", "Statement2"] This is how I am splitting the array result = statement.split(", ") The output what I want is: Statement1 Statement2 But I am getting the error as: undefined method `split' for ["Statement1", "Statement2"]:Array (NoMethodError) Can someone please help me? Thanks in advance |
bundle exec rake db:migrate worked, but development.sqlite3 is empty Posted: 27 Dec 2016 06:09 AM PST I'm new to RoR. The following line executed normally: bundle exec rake db:migrate Output showed that it is migrated. development.sqlite3 and production.sqlite3 were created but empty, although schema.rb was written properly. Also I executed: bundle exec rake db:test:prepare test.sqlite3 is created and also written properly. This is the content of the file inside the migration file: class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.timestamps end end end Kindly help me solve the problem. Let me know if any other details need to be specified. |
Post new form on every site Posted: 27 Dec 2016 07:31 AM PST I would like to create a post from a form. This is what I did and what worked so far: View <%= form_for @post, url: {action: "create"}, html: { multipart: true } do |form| %> <%= form.text_field :description %> <%= form.file_field :image %> <%= form.hidden_field :user_id, :value => current_user.id %> <%= submit_tag"Post", class: "btn" %> <% end %> Controller def new @post = Post.new(params[:post]) end def create @post = Post.create(post_params) if @post.save redirect_to @post else render :new end end def post_params params.require(:post).permit(:description, :image, :user_id) end But now I would like to create a from, which will be placed in the layouts/application.html.erb and acceable from every route/site. But my problem is, that the variable @post is missing, because I parse it in the new function of the post itself. Any idea how to solve this? |
Rspec and Capybara , what is the difference between visit and get Posted: 27 Dec 2016 07:02 AM PST My spec/controllers/undertakings_controller_spec.rb is below. RSpec.describe UndertakingsController, type: :controller do describe 'redirect with home due to login user' do subject {current_path} it 'can get with authenticate undertaking user' do login_user @undertaking.user #get :show , id: @undertaking visit undertaking_path(@undertaking) expect(response).to redirect_to root_path end end end This has error (Expected response to be a , but was <200>). But when I change ( visit undertaking_path(@undertaking) ) to ( get :show , id: @undertaking ) , this does not have the error. What is the difference between visit and get? I read Rspec and capybara, difference between visit and get methods, with regards to the current_path object but I can't understand the error in this case. Please help me. Anyway, My controllers/undertakings_controller.rb is below. class UndertakingsController < ApplicationController before_action :undertaking_not_have_comment , only: [:show] def show @undertaking=Undertaking.find(params[:id]) @asking=@undertaking.asking @comment=Comment.new do |c| c.user=current_user end end private def undertaking_not_have_comment @undertaking=Undertaking.find(params[:id]) if current_user == @undertaking.user unless @undertaking.comments.count > 0 redirect_to root_path end end end |
Rails 5 Securing Action Cable with redis Posted: 27 Dec 2016 05:18 AM PST What can I do to secure socket connection in rails 5 with redis and action Cable? What configuration we can add in config/redis.rb to add password authentication in Redis. |
How to query a field by name on mongoid? Posted: 27 Dec 2016 04:59 AM PST How can I get the same query's result : Test.where(name: "Depeche Mode").first.last_connection_date Changing last_connection_date by a String @desired_field = last_connection_date Test.where(name: "Depeche Mode").first.(@desired_field) |
How to get a most recent value group by year by using SQL Posted: 27 Dec 2016 05:02 AM PST I have a Company model that has_many Statement . class Company < ActiveRecord::Base has_many :statements end I want to get statements that have most latest date field grouped by fiscal_year_end field. I implemented the function like this: c = Company.first c.statements.to_a.group_by{|s| s.fiscal_year_end }.map{|k,v| v.max_by(&:date) } It works ok, but if possible I want to use ActiveRecord query(SQL), so that I don't need to load unnecessary instance to memory. How can I write it by using SQL? |
Rails 'rake task' execute in ‘RAILS_ENV=production' with nohup Posted: 27 Dec 2016 05:41 AM PST I have rake task which continuously need to be active. Whenever I ran it by command RAILS_ENV=production rake jobs:abc it works fine but when I close terminal rake job get stopped.So I found other solution on it by using nohup to run it in background. I execute command: nohup RAILS_ENV=production rake jobs:work & but it gives error: nohup: failed to run command 'RAILS_ENV=production': No such file or directory Please suggest, to way execute rake task in a production environment. |
cloud9 postgresql custom definition Posted: 27 Dec 2016 04:32 AM PST with cloud9 and Rails, I want to access a database with these parameters : database: mydatabase username: myusername password: mypassword What is the process to achieve that ? |
Rails Application for parsing content and filter only the reply part using gmail gem Posted: 27 Dec 2016 04:42 AM PST What I want to do is using scheduler task which checks for the incoming emails periodically and Parse the content and filter only the reply part of comments using gmail gem.I wrote scheduler task but I am not getting how to parse the content and filter only reply parts? I have created rake task like this: namespace :mail_comment do desc "TODO" task reply_to_comments: :environment do end end I have used whenever gem for that and inside schedule.rb, I wrote every 1.day do rake "mail_comment:reply_to_comments" end Could anyone please help me regarding this doubt? Thanks. |
How to add new attachinary image to an instance instead of replacing the whole array in Rails 5 Posted: 27 Dec 2016 07:27 AM PST This might be a stupid question since I can't find it already asked here but I can't find a solution no matter how I tried. I use Rails 5 with Cloudinary and Attachinary gems. I have a model PointOfInterest with has_attachments :photos, maximum: 3 Everything works fine if photos are uploaded at once (with simple_form ). But I want my users to be able to upload photos sequentially ; for instance 1 photo at the creation of the point_of_interest and then add 2 more later on edit . Unfortunately the update method deletes the attachments before saving the new input. I ended up building an array with the old attachment and new one from the update and tried to overwrite the attachments: @point_of_interest.photos = new_photoset but I get a Runtime error => Can't modify frozen hash . I also just realized my new_photoset array mixes Attachinary::File (previous image) and Attachinary::File::ActiveRecord_Associations_CollectionProxy (new image) so I'm pretty sure I'm not on the right track. I tries many different approaches and I don't find the Attachinary docs very helpful. Or maybe I should investigate on the jQuery-File-Upload side? Any help will be much appreciated. |
Rails 5: jsTree view using AJAX for grouped records from single table Posted: 27 Dec 2016 05:12 AM PST I'm trying to implement jsTree populating tree using AJAX. In my view (/index.html.erb) I have dropdown which on select finds all placements related to particular media. There is controller which looks like this: /controllers/inventory/manage_inventory_controller.rb def index @media = Media::Media.where(company_id: user_companies) end def update_placements @placements = Placements::Radios.joins(positions: :media).where('media_id = ?', params[:media_id]) respond_to do |format| format.js end end I have model /models/placements/radios.rb which looks like this: module Placements class Radios < ApplicationRecord default_scope { order({adbreaks: :desc}, :status) } has_many :radios, dependent: :destroy, class_name: 'Items::Radios' belongs_to :positions, optional: true, inverse_of: :radios, class_name: 'Positions::Positions' enum general: { available: 1, full: 2, closed: 3}, _suffix: true jsonb_accessor :spots, first: [:integer, store_key: :f], second: [:integer, store_key: :s], other: [:integer, store_key: :o, array: true, default: []], before_last: [:integer, store_key: :bl], last: [:integer, store_key: :l] def self.year_placements Placements::Radios.group_by_year(:adbreaks, time_zone: false).count end def self.month_placements Placements::Radios.group_by_month(:adbreaks, time_zone: false).count end def self.day_placements Placements::Radios.group_by_day(:adbreaks, time_zone: false).count end end end With help of the gem Groupdate I've created def's for grouping records by year, month and day. My routes look like this: namespace :inventory do resources :manage_inventory, only: [:index, :new, :create, :edit, :update] end get '/manage_inventory/update_placements', to: 'inventory/manage_inventory#update_placements' There is update_placements.js.coffee file which renders partial below with this code: $("#placements_tree").html '<%=j render 'inventory/manage_inventory/placements_radio' %>' At the moment I have partial _placements_radio.html.erb where jsTree plugin is populated: <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-content"> <div id="placements_radio_json"></div> </div> </div> </div> <%= javascript_include_tag 'inventory/placements_radio', 'data-turbolinks-track': true %> jsTree template for AJAX code (CoffeeScript) is this: $ -> $('#placements_radio_json').jstree 'core': 'data': 'url': '//www.jstree.com/fiddle/?lazy' 'data': (node) -> { 'id': node.id } return In same index.html.erb where I have <div id='placements_tree'></div> where I want to populate jsTree when particular Media (:media_id) is selected. My desired result would look like this: - On dropdown select, for particular Media there is jsTree of related Placement records populated
- Tree structure would be like this:
- Year
- Month
- Day
- All records row-by-row for particular day
How to define AJAX part and connect all of this together, please? Thank you for any help! |
Not able to place csv data in a Hash Posted: 27 Dec 2016 06:51 AM PST I have a CSV file with two columns: PPS_Id Amount 123 100 1234 150 I read data from this file and insert in a array using the code below: CSV.foreach("filename.CSV", headers: true) do |row| file_details << row.inspect # hash end I am then trying to push the data in the file_details into a hash with PPS_Id as key and Amount as Value, I am using the code below: file_details_hash = Hash.new file_details.each { |x| file_details_hash[x['PPS_Id']] = x['Amount'] } But when I print the result I get nothing just {"PPS_Id"=>"Amount"} Can you please help |
multiple user types with self references rails Posted: 27 Dec 2016 03:53 AM PST I am working on an app in rails where I need to make multiple types of users. I am using Devise gem for authentication. Now let me give you an overview what I am trying to achieve and could not for past whole week. First, I want 2 types of users. Let us call them Client and Developer as shown below. class Client < ActiveRecord::Base end class Developer < ActiveRecord::Base end Now, these 2 users have many to many relation with each other. A client can have many developers and a developer can also work for many clients. So, for that, we will need a middle table as well. Let us call it client_developer_join. So, let us update our models accordingly. class Client < ActiveRecord::Base has_many :developers, through: :client_developer_joins, dependent: :nullify has_many :client_developer_joins, dependent: :destroy end class Developer < ActiveRecord::Base has_many :clients, through: :client_developer_joins, dependent: :nullify has_many :client_developer_joins, dependent: :destroy end class ClientDeveloperJoin < ActiveRecord::Base belongs_to :client belongs_to :developer end Important: Now, what I want is that when a user sign up, he will be given the ability to choose whether to sign up as a Client or a Developer using radio buttton or some other good looking thing. There will also be a third option named "Both". In that case, user will have the option to switch from Client to Developer and vice versa whenever he wants. How can I acheive without creating multiple sign up and sign in forms for each type of user and give them the ability to switch. I have looked into STI (Single Table Inheritance) and all the questions on StackoverFlow related to that but could not solve the problem. One solution that I think is ideal but do not know how to achieve is to have seperate devise models for each type of user but that will create different sign up and sign in forms for that. I do not want that and it will also not give me the ability to switch from the one type to another type. |
Mongoid is not recognizing relations created by PyMongo Posted: 27 Dec 2016 03:35 AM PST I have 2 models: class User include Mongoid::Document include Mongoid::Timestamps include Mongoid::Enum include Mongoid::Attributes::Dynamic has_one :normal end class Normal include Mongoid::Document include Mongoid::Timestamps include Mongoid::Attributes::Dynamic belongs_to :user end The normal is created using a service written in python that uses pymongo lib to create and update it. The way it is created is by populating the {attr1:x, .., attrn:n, user_id: user_id(string)} and saving to Mongodb. What happens is that: user.normal = nil while normal.user = user not nil. I can't seem to find a way to keep the relation. Anybody know what I am missing?? |
cannot save a record using has many through in rails 5 Posted: 27 Dec 2016 03:36 AM PST I and not able to find why the record cannot be saved into the database...Help me find what I did wrong in my models and controllers. User.rb has_many :interested_users_lists has_many :interested_posts, through: :interested_users_lists accepts_nested_attributes_for :interested_users_lists, :interested_posts ...etc InterestedUsersList.rb class InterestedUsersList < ApplicationRecord # belongs_to :post # belongs_to :users belongs_to :interested_post, class_name: 'Post' belongs_to :interested_user, class_name: 'User' end Post.rb belongs_to :owner, :class_name => "User", :foreign_key => "user_id", touch: true has_many :interested_users_lists, dependent: :destroy has_many :interested_users, through: :interested_users_lists accepts_nested_attributes_for :interested_users_lists, :interested_users etc... method I used: # add interested user def add_interested_user(user) puts "this is user id: #{user.id} " interestedUser = self.interested_users_lists.build(user_id: user.id) interestedUser.save puts "this is #{interested_users_lists.first.user_id} " end Migration file class CreateInterestedUsersLists < ActiveRecord::Migration[5.0] def change create_table :interested_users_lists do |t| t.integer :user_id t.integer :post_id t.timestamps end end end posts_controller.rb def interested @post.add_interested_user(current_user) #cannot be saved... end ... private def post_params params.require(:post).permit(:subject, :price, :category, :street_address, :city, :state, :zip, :condition, :payment_method, :content, post_attachments_attributes: [:id, :post_id, :avatar], interested_users_lists_attributes: [:id, :post_id, :user_id]) end development log Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? ORDER BY "posts"."created_at" DESC LIMIT ? [["id", 1], ["LIMIT", 1]] this is user id: 2 **(0.0ms) begin transaction (0.1ms) rollback transaction** _why???_ InterestedUsersList Load (0.1ms) SELECT "interested_users_lists".* FROM "interested_users_lists" WHERE "interested_users_lists"."post_id" = ? [["post_id", 1]] this is 2 Redirected to http://localhost:3000/users/posts/2 Completed 302 Found in 77ms (ActiveRecord: 4.9ms) Started GET "/users/posts/2" for ::1 at 2016-12-27 03:04:33 -0800 |
Render images from enother project cause 404(not found) error Posted: 27 Dec 2016 05:59 AM PST Hello I have to separate projects, images_project and site_project. site_project should render images from images_project only in development environment from local machine. In production it does by SDN. I share images_project path from secrets in 'praser_path'. I added images path to assets config in site_project: # config/initializers/assets.rb if Rails.env.development? && Rails.application.secrets.parser_path # share parser images for admin Rails.application.config.assets.paths.push( File.join( Rails.application.secrets.parser_path, 'public', 'uploads') ) Rails.application.config.assets.precompile += %w( advert_image/** ) end My model looks for images in local machine # model/image.rb def file_url(size=nil) if Rails.env.development? && Rails.application.secrets.parser_path File.join( Rails.application.secrets.parser_path, 'public', file.url(size)) else REMOTE_HOST + file.url(size) end end But when a page with my images renders it processes 404 for all images with this error: http://localhost:3000/Users/nick/CODE/work/biz/parser/public/uploads/advert_image/images/374/micro_3117094366.jpg Failed to load resource: the server responded with a status of 404 (Not Found) I know that the follow link is bad and images is in file:///Users/nick/CODE/work/biz/parser/public/uploads/advert_image/images/374/micro_3117094366.jpg What should I do to get around the server and render images straight from local machine? |
devise_ldap_authenticatable not wotking Posted: 27 Dec 2016 01:54 AM PST Try yo use devise_ldap_authenticatable gem in my app, but it's not working. Authorization page return invalid email or password error and Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms) in server logs. ldap.yml authorizations: &AUTHORIZATIONS allow_unauthenticated_bind: false group_base: "dc=dvfu,dc=ru" development: host: dc.dvfu.ru port: 389 attribute: cn base: dc=dvfu,dc=ru admin_user: CN=usertest,OU=Service,DC=dvfu,DC=ru admin_password: 'password' ssl: no <<: *AUTHORIZATIONS And i have no idea how to debug it, devise_ldap_authenticatable documentation is poor. Oh, maybe it's important i have username or email authethication in my app, so have to rewrtie one line in on class: auth_key = self.authentication_keys.first was chanhged to auth_key = :username Devise::Models::LdapAuthenticatable::ClassMethods.class_eval do def find_for_ldap_authentication(attributes={}) #auth_key = self.authentication_keys.first auth_key = :username return nil unless attributes[auth_key].present? auth_key_value = (self.case_insensitive_keys || []).include?(auth_key) ? attributes[auth_key].downcase : attributes[auth_key] auth_key_value = (self.strip_whitespace_keys || []).include?(auth_key) ? auth_key_value.strip : auth_key_value resource = where(auth_key => auth_key_value).first if resource.blank? resource = new resource[auth_key] = auth_key_value resource.password = attributes[:password] end if ::Devise.ldap_create_user && resource.new_record? && resource.valid_ldap_authentication?(attributes[:password]) resource.ldap_before_save if resource.respond_to?(:ldap_before_save) resource.save! end resource end end |
ruby on rails secuirity [on hold] Posted: 27 Dec 2016 01:40 AM PST In term to performing penetration testing with one of the tool Vega then its giving error of flag not set of cookie. And then I have set it to secure: true for a session in the config file but still same response from Vega. Log of Vega is below: Vega has detected that this cookie was set without the Secure flag. When the Secure flag is set, the browser will only transmit the cookie back to the server over HTTPS. However, when this flag is not set, the cookie may be transmitted over unencrypted HTTP. This may allow the cookie to be observed in transit. Please let me know if any suggestion..Quick response will help me more Thanks |
One form three tables in ruby on rails Posted: 27 Dec 2016 04:55 AM PST I want to create a single form to save data to 3 tables. 3 tables are connected with one to many relation. I am able to save data to brandname but not to producttype and sub category. below is the code: <%= form_for(@brandname, :html => {class: "form-horizontal", role: "form"}) do |f| %> <div class="form-group"> <div class="control-label col-sm-2"> <%= f.label :brandname %> </div> <div class="col-sm-8"> <%= f.text_field :brandname, class: "form-control", placeholder: "Enter Brand Name" %> </div> </div> <div class="form-group"> <%= f.fields_for :producttype do |builder| %> <div class="control-label col-sm-2"> <%= builder.label :content, "Type Of Product" %><br /> </div> <div class="col-sm-8"> <%= builder.text_field :content, class: "form-control", placeholder: "Enter Product Type" %> </div> <% end %> </div> <div class="form-group"> <%= f.fields_for :subcategories do |builder| %> <div class="control-label col-sm-2"> <%= builder.label :content, "Sub Category" %><br /> </div> <div class="col-sm-8"> <%= builder.text_field :content, class: "form-control", placeholder: "Enter Sub Category" %> </div> <% end %> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <%= f.submit(@brandname.new_record? ? "Add" : "Save", class: 'btn btn-primary btn-lg') %> <%= link_to "Cancel", new_brandname_path, class: "btn btn-default btn-lg active" %> </div> </div> <% end %> Controller: def new @brandname = Brandname.new @brandname.producttypes.build producttype.subcategories.build end def create @brandname = Brandname.new(prodinfo_params) if @brandname.save flash[:success] = "ProductInfo Created Successfully" redirect_to root_path else render 'new' end end private def prodinfo_params params.require(:brandname).permit(:brandname, :producttype, :subcategory ) # producttype_attributes: [:producttype] end Model: Brandname: class Brandname < ApplicationRecord has_many :producttypes, :dependent => :destroy accepts_nested_attributes_for :producttypes end Producttype: class Producttype < ApplicationRecord belongs_to :brandname has_many :subcategories, :dependent => :destroy accepts_nested_attributes_for :subcategories end Sub Category: class Subcategory < ApplicationRecord belongs_to :producttype end Can someone help me with this? |
Render the submit button from another controller Posted: 27 Dec 2016 01:17 AM PST I'm trying to render form(form2) into another form(form1). Both forms have the submit button. Both buttons work like submit button but only for form1 has the error "NoMethodError at form1: undefined method `save' for nil:NilClass" and params: "form1_params"=>{"form1_title"=>"title1", "form1_count"=>"1"}, "form2_params"=>{"form2r_name"=>"name2", "form2_value"=>"1"}, "commit"=>"add", "controller"=>"form1", "action"=>"create"} form1: = form_for @form1 do |f| = render 'form2/new' = f.submit 'Submit', class: 'btn btn-success', id: 'sav_bonuse1' form2: = form_for(@form2, url: form2_path) do |f| = f.submit 'Submit', class: 'btn btn-success', id: "save" create action in form1_controller: def create @form1 = Form1.new(form1_params) if @form1.save flash[:success] else flash[:error] end redirect_to form1_path end How I can fix both this buttons? |
No comments:
Post a Comment