Save from params to JSONB datatype column using Postgres Posted: 16 Nov 2016 08:28 AM PST I'm kinda new working with JSONB datatype column and I'm having some trouble saving the data the way I'd like to my database in Ruby on Rails. I'd like to save the data as follows: col = [{"k1"=>"v1","k2"=>"v2"},[{"sk1"=>"sv1","sk2"=>"sv2"},{"sk1"=>"sv1","sk2"=>"sv2",...,{"sk1"=>"sv1","sk2"=>"sv2"}]] So basically an Array that has 2 elements, first being a Hash, and second being an Array of n Hashes, not necessarily the same number between records. I want to save like this because I want to be able to do something like: x.col[1].each do |y| puts y["sk1"] end The data comes from a Form and I'm saving it directly from Params, and it's saving as follows: {"0"=>{"k1"=>"v1", "k2"=>"v2"}, "1"=>{"0"=>{"sk1"=>"a", "sk2"=>"b"}, "1"=>{"sk1"=>"c", "sk2"=>"d"}}} It saves exactly as the Params look like. I'd like to get rid of the indexes, because I can't iterate through the inner Array to retrieve the data. 1) Is it possible to save the data the way I'd like? 2) How do I get rid of the indexes when I save the data to the database? 3) Is it a correct approach to doing this? |
How to create an object from array by calling back create action? Ruby on rails Posted: 16 Nov 2016 08:18 AM PST I am stuck at: I need to create a text and the same way I need to create a list of words out of the created text. So what I did: I created create action in my text controller: def create @text = Text.new(text_params) if @text.save redirect_to text_path(@text), notice: "Text successfully created" else render :new end end Here is the form for creating a text: <%= form_for @text do |f| %> <div class="form-group"> <label>Text name</label> <%= f.text_field :name %> </div> <div class="form-group"> <label>Description</label> <%= f.text_area :description%> </div> <div class="actions"> <%= f.submit "Save", class: "btn btn-primary" %> </div> <%end%> In the Text Model I created after_create callback: class Text < ApplicationRecord has_many :words after_create :create_words def create_words @word = Word.new( word_params ) @text.split(/\W+/) @text.each do |splitted| if splitted != @words.name splitted = @word @word.save redirect_to root_path else render :new end end end def word_params params.require(:word).permit(:name, :translation) end end I am new to RoR and Please help me out to fix my issue. Basicly what I need is when I am creating text for instance a text is: I have a dog should be placed on my textdatabase and each word: I, have, a, dog should be placed in my Word database. Thank you very much in advance. |
Ruby on Rails : relationship with "has_many" Posted: 16 Nov 2016 08:30 AM PST Mr X likes only one post made by Mr Y How can I create a relationship between Mr X and Mr Y to see the Mr Y's posts? (to see the suggested posts) user.rb has_many :posts has_many :liked_posts, through: :liked, source: :post post.rb def liked_by?(user) likes.where(user: user).any? end likes.rb # id :integer not null, primary key # user_id :integer not null # like_id :integer not null Should I use uniq ? |
Why can't I establish two cleave.js formatted fields in the same js file? (Ruby on Rails) Posted: 16 Nov 2016 08:15 AM PST I want to format both phone and credit card input using cleave.js (in rails). I've got the formatting working if I only declare one new Cleave object, but I get this error if I attempt to declare two: Uncaught Error: [cleave.js] Please check the element Here's the relevant parts of the JS file: var Global = {}; Global.onLoad = function(){ Global.setupDatepickers(); //unrelated function Global.setupCleavePhone(); Global.setupCleaveCreditCard(); }; $(document).on('turbolinks:load', function(){ Global.onLoad(); }); Global.setupCleavePhone = function() { new Cleave('.phone-input', { phone: true, phoneRegionCode: 'US', delimiter: '-' }); } Global.setupCleaveCreditCard = function() { new Cleave('.card-input', { delimiter: '-', blocks: [4,4,4,4] }); } I've tried a few remixes of this including assigning the Cleave objects to variables and declaring them in the same function, but no dice. Here's a jsfiddle of multiple cleave objects being delared at once, and I can't see any meaningful differences between my code and theirs. The selector classes are properly applied in the view. Any thoughts why I can't seem to format two fields at once? |
Bad Redirect On Create Method - Rails 4 Posted: 16 Nov 2016 08:06 AM PST I am trying to change the redirect when I create a listing, but I keep getting a No route matches {:action=>"manage_photos", :controller=>"listings"} missing required keys: [:id] . What am I missing? My route is nested and there is a manage_photos method in my controller. Not sure where to go from here. routes.rb resources :listings do member do get 'like' get 'unlike' get 'duplicate' get 'gallery' delete 'gallery' => 'listings#clear_gallery' get 'manage_photos' get 'craigslist' get "add_to_collection" get 'request_photos' get 'rsvp' end end rake routes: manage_photos_listing GET /listings/:id/manage_photos(.:format) listings#manage_photos listings_controller: create method: def create @listing = Listing.new(listing_params) respond_to do |format| if @listing.save format.html { redirect_to manage_photos_listing_path, notice: 'Listing was successfully created.' } format.json { render json: @listing, status: :created, location: @listing } else format.html { render action: "new", notice: "Correct the mistakes below to create the new listing" } format.json { render json: @listing.errors, status: :unprocessable_entity } end end end manage_photos method: def manage_photos @listing = Listing.find(params[:id]) end error: |
Is it possible not to get 2 last elements via nokogiri? Posted: 16 Nov 2016 08:01 AM PST I want to take all <p> elements, using this code: novelty.body = page.css('.rt-article p').text But I don't want to get last 2 <p> elements. Is it possible to do? Thanks. |
How to send custom headers in open-uri (ruby) and check them Posted: 16 Nov 2016 08:27 AM PST Found this in the following doc:https://ruby-doc.org/stdlib-2.1.0/libdoc/open-uri/rdoc/OpenURI.html Additional header fields can be specified by an optional hash argument. open("http://www.ruby-lang.org/en/", "User-Agent" => "Ruby/#{RUBY_VERSION}", "From" => "foo@bar.invalid", "Referer" => "http://www.ruby-lang.org/") {|f| # ... } Can someone tell how to check whether they are properly working. |
rails with ajax retrive data from database Posted: 16 Nov 2016 07:44 AM PST I am basic to rails and Ajax. I have rails query to retrieve data from three table using JOINS. I want to retrieve data by selecting the date option, result should same page enter image description here Following is the rails Query @query = ItemType.select("name, item_id, sum(quantity) as Total_Quantity_Itemwise, sum(price_value) as Item_Total_Amount, price_value, order_items.created_at Date").joins('INNER JOIN items ON items.item_type = item_types.id', 'INNER JOIN order_items ON order_items.item_id = items.id').group("item_id").order(" order_items.created_at") |
Rails routing with hyphenated name in path Posted: 16 Nov 2016 07:43 AM PST Im having trouble with some routing due to a user with a hyphenated last name. My route reads get '/team/:first_name-:last_name', to: 'home#employee', as: :employee For something like "/john-smith" this would obviously work fine, but for an employee with a hyphenated last name such as "Sarah Jane-Smith" that results in "/sarah-jane-smith." Rails is splitting on the second hyphen, which throws an error as that name doesnt exist. SELECT "employees".* FROM "employees" WHERE (first_name = 'sarah-jane' AND last_name = 'smith') Is there a simple way to change the route interpretation without having to overhaul my routing for employees? Thanks in advance. |
before_create method in model not working when a user is created - Rails4 Posted: 16 Nov 2016 07:36 AM PST - i am unsure why my code is not working - your help would be much appreciated
- what i want to do is: when a user is created the user is assigned to the role "Client" and the group "Client Group"
question: i am unsure why my before_create action is not working. could one kindly advise me on this? i get the error message: NoMethodError - undefined method `name' for nil:NilClass: i find that strange as when i check my category in my terminal all is seems fine user.rb user belongs_to :category_role user belongs_to :category_managementgroup before_create :assign_user_to_role_and_group def assign_user_to_role_and_group self.category_role.name == "Client" self.category_managementgroup.name == "Client Group" end category_role.rb has_many :users category_managementgroup.rb has_many :users seed.rb CategoryRole.delete_all cr01 = CategoryRole.create!(name:'Admin') cr02 = CategoryRole.create!(name:'Primary Admin') cr03 = CategoryRole.create!(name:'Client') CategoryManagementgroup.delete_all cmr01 = CategoryManagementgroup.create!(name:'Administration Group') cmr02 = CategoryManagementgroup.create!(name:'Client Group') cmr03 = CategoryManagementgroup.create!(name:'Management Group') schema create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.integer "category_role_id" t.integer "category_managementgroup_id" end create_table "category_roles", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "category_managementgroups", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end |
Form field per table row in Rails Posted: 16 Nov 2016 07:53 AM PST I have a settings table in my Rails app that has the following columns: id, name, value An example of some sample data might be: id: 1, name: 'site_name' value: 'Cameron' id: 2 name: 'email' value: 'cameron@example.com' What I want to do is have a page where I list these settings as simple text fields that I can then edit and save back into the database. I have the following controller method that lists them: def index @settings = Setting.all end And then display them in the view like so: <% @settings.each do |setting| %> <div class="form__group"> <label class="form__group__label"><%= setting.name %></label> <div class="form__group__input"> <input type="text" name="setting[<%= setting.name %>]" value="<%= setting.value %>"> </div> </div> <% end %> Which displays them fine. But how do I save them? I was thinking about looping through them in the controller like: def update_settings params[:setting].each do |setting| # somehow update each param sent back... end end |
Rails: param is missing or the value is empty: create Posted: 16 Nov 2016 07:06 AM PST I'm trying to build a button that allows users to vote on certain things they like. All of my tests pass, but when I click the like vote button I get this error: vote: param is missing or the value is empty: create So something is clearly wrong with my code. I understand that this has to do with strong params and that a vote param is not being passed even though it is supposed to be because of params.require(:vote) vote_form.html.erb <% unless current_user.votes.pluck(:food_id).include?(food.id) %> <%= form_for :vote, url: votes_path do |f| %> <%= hidden_field_tag 'food_id', food.id %> <%= hidden_field_tag 'user_id', food.user.id %> <%= submit_tag "Vote", :class => "like_button" %> <% end %> <% else %> <% vote = food.votes.where(user_id: current_user.id).first %> <div class="unlike_button"> <%= button_to "Unlike", vote_path(vote), method: :delete %> </div> <% end %> class VotesController < ApplicationController def index @votes = Vote.all end def new @vote = Vote.new end def create @vote = Vote.new(vote_params) if @vote.save flash[:notice] = "Thanks for voting!" redirect_back(fallback_location: root_path) else flash[:notice] = "Something went wrong" redirect_back(fallback_location: root_path) end end def destroy @vote = Vote.find(params[:id]) if @vote.destroy! flash[:notice] = "Unvoted!" redirect_back(fallback_location: root_path) end end private def vote_params params.require(:vote).permit(:food_id, :user_id) end end describe "POST #create" do before(:each) do @user = create(:user) sign_in(@user) @food = create(:food) end context "with valid attributes" do let(:vote_params) { FactoryGirl.attributes_for(:vote).merge(:user_id => @user, :food_id => @food) } it "creates a new vote" do expect { post :create, params: { vote: vote_params } }.to change(Vote, :count).by(1) end it "Updates @user vote count" do expect { post :create, params: { vote: vote_params } }.to change(@user.votes, :count).by(1) end it "Updates @food vote count" do expect { post :create, params: { vote: vote_params } }.to change(@food.votes, :count).by(1) end end end |
Override user filters in Spree Admin Posted: 16 Nov 2016 06:52 AM PST I have a problem with customising Spree. Any ideas how can I override this search box so that I can provide my custom added field to Spree::User localhost:3000/admin/users I've override view already app/views/spree/admin/users/index.html.erb <%= f.text_field :bill_address_company_cont, class: 'form-control' %> to <%= f.text_field :my_field_name_cont, class: 'form-control' %> but I get error undefined method my_field_name_cont' for #<Ransack::Search:0x007fc2c0775e18> |
How to do two actions in one action of the controller Posted: 16 Nov 2016 08:13 AM PST I need to create some text. I have a create action: def create @text = Text.new(text_params) if @text.save redirect_to text_path(@text), notice: "Text successfully created" else render :new end end and the form: <%= form_for @text do |f| %> <div class="form-group"> <label>Text name</label> <%= f.text_field :name %> </div> <div class="form-group"> <label>Description</label> <%= f.text_area :description%> </div> <div class="actions"> <%= f.submit "Save", class: "btn btn-primary" %> </div> <%end%> I need to have two action when I am submitting my text. The first action is going to create a text. The second is to create words out of the text words and should make a list of words. When creating a word I need to have an if statement create a word if not present. I am now having an issue with how I can split and create each word: def create_words @text.split(/\W+/) @text.each do |splitted| if splitted !== @words.name splitted = @word @word.save redirect_to root_path end end |
PaperTrail: touch_with_version does not persist version when one version already was persisted Posted: 16 Nov 2016 06:16 AM PST I need your help! I'm trying to generate a version for a child manually when the parent is updated using touch_with_version . I store the version id of the child as an attribute (belongs_to relation) in the parent model. However this works only the first time. The second time I call touch_with_version the version id is incremented, but the version is not persisted to the database (postgres9.6)! If I call touch_with_version 10 times and I inspect the last version object it has the id 10 but only the first one (id=1) is persisted and the total size of versions is always 2. Do you have any hint for me? The code looks like the following in the end: class Parent< ActiveRecord::Base after_update :update_child_version, if: :completed? # ... def update_child_version parent.paper_trail.touch_with_version # child = belongs_to_relation where the child is a paper_trail model # child_version = belongs_to_relation with foreign key to the custom version table for the child model self.class.update_all child_version_id: child.versions.last.id # This call works the first time, but as soon as a record is persisted only the versions.last.id gets incremented but not persisted so i get a foreign key violation error :-( end # ... end Maybe it's helpful, the child model looks somehow like this: class Child < ActiveRecord::Base # ... class Version < PaperTrail::Version self.table_name = :child_versions self.sequence_name = :child_versions_id_seq end # Because I create versions using touch_with_version I ignore all other events has_paper_trail on: [], class_name: Child::Version.name # ... end Any thoughts on this? Greetings from Germany Florian |
Get <a> content via Nokogiri Posted: 16 Nov 2016 06:13 AM PST I'm trying to get a content of <a> element via Nokogiri by doing the following: novelty.title = page.at_css('h1 a') It saving to database like this: <a href="a_link_to_a_novelty_title">A title</a> . So, how can I get only A title from the <a> tag? Thanks. |
How can i implement payment through Paypal on Sharetribe opensource? Posted: 16 Nov 2016 06:06 AM PST i'm trying to implement payment through Paypal on the opensource version of Sharetribe (https://github.com/sharetribe/sharetribe). By default Sharetribe doesn't allow people to use Paypal with the opensource code. How can i create the transaction using the Paypal API? Thank you! |
Rspec not matching my route Posted: 16 Nov 2016 06:08 AM PST I have post '/foo/bar', to: 'api/v1/things#bar' in my routes.rb . Running rails routes returns foo_bar POST /foo/bar(.:format) api/v1/things#bar I'm trying to test it with post '/foo/bar' , but I get No route matches {:action=>"/foo/bar", :controller=>"api/v1/things"} I know the problem is something silly, but I'm unable to see it. Any ideas? |
prevent rails server from launching if file doesnt exist Posted: 16 Nov 2016 05:49 AM PST I have aws.yml development: asset_host: 'abcd1234efgh@cloudfront.net' I created assets.rb AWS_CONFIG = Rails.application.config_for(:aws) unless (AWS_CONFIG.nil? || AWS_CONFIG['asset_host'].nil?) Rails.application.config.asset_host = AWS_CONFIG['asset_host'] end I am trying to implement the logic if aws.yml not exists then it should completely blow up and prevent the rails server from launching. Any idea how could i achieve that? |
Ruby on Rails random code inserted in static pages, tests RED Posted: 16 Nov 2016 05:49 AM PST After getting through the first five chapters of Michael Hartl's Ruby on Rails Tutorial book, I ran my test as usual before doing my GitHub and Heroku push, but got RED. I checked my static pages and all of them had 'HEAD =========>>>>>>>rails-flavored-ruby' inserted into them at random places in the HTML. Not only that, my static_pages_controller and routes.rb was mangled in the same way. 'rails-flavored-ruby' was one of the git branches I created for the tutorial, so I have a suspicion that one of my git commands would have altered my files, if that is even possible. Does anyone else have this problem going through the tutorial, where did I go wrong and what can I do to fix this app I have been building for the last three chapters. |
Ruby on Rails ActiveRecord what does .anything do after a find? Posted: 16 Nov 2016 06:00 AM PST I have the following Code: @contacts = Project.find(params[:project_id].to_i).contacts Can someone explain me what does .contacts part do at the end of this line? I try to figure out, but i can't find a answer. I think it must be something like a include or something, but I really don't understand. Would be really happy for any advise (maybe only a link to a explanation would be enough. I tried to find something but i don't know what i've to search because i've no idea what this is..) |
Force HTTPS/SSL for all controller/request specs in rspec Posted: 16 Nov 2016 05:13 AM PST I'm using RSpec 3.5.0, and would like to enable HTTPS/SSL requests for all my specs. Since I added force_ssl to my ApplicationController , all my specs are failing, since they are redirecting to the secure version of the site instead of rendering, etc. |
Rails 5, Ajax, jQuery - Cant send received data to particular element Posted: 16 Nov 2016 08:31 AM PST So, I have partial where is a table row and different table datas. By clicking a button (which is in <tr> ) I send Ajax request (simply, with remote: true ) and also update item data (displayed in <tr> ) with action. It all goes fine, but I can't send received data from Ajax to specific <td> . If more items being displayed - all of them receives that data. _partial.html.erb: <body> <div> <tr data-line-item-id='<%= line_item.id %>' class='line-item'> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"></div> <div class="col-sm-10"> </div> </div> </td> <td data-th="Price"><%= number_to_currency(line_item.product.price) %></td> <td data-th="Quantity"> <%= line_item.quantity %> </td> <td data-th="Subtotal" class="text-center" class="subtotal"> <%= number_to_currency(line_item.total_price, :unit => "€", separator: ",", format: "%n %u") %></td> <td class="actions" data-th=""> <td><%= link_to "-", decrease_line_item_path(product_id: line_item.product), remote: true %></td> <td><%= link_to "+", increase_line_item_path(product_id: line_item.product), remote: true %></td> </td> </tr> </div> </body> decrease.js.erb: $("td[data-th='Quantity']").html('<%= @line_item.quantity %>'); My 'nice tries' were something like: $(this).parent().parent().find("td[data-th='Quantity']").html('<%= @line_item.quantity %>'); But my 'best achievement' was to update only the particular, found by number item, like this: $("td[data-th='Quantity']").eq(0).html('<%= @line_item.quantity %>'); Otherwise they all get updated... UPDATE This, kinda made it working, but if I increase numbers of one item and then increase other item numbers, first click shows the number of previously updated item number... But answer is close. Hope someone could help... Many thanks increase.js.erb: $(document).ready(function(){ $('.increase').click(function(){ var element = $(this).parent().parent() $(element).find("td[data-th='Quantity']").html('<%= @line_item.quantity %>'); }); }); |
Getting hash tree of trees belonging to an association Posted: 16 Nov 2016 05:01 AM PST Even though I think this is a fairly common problem, I've not been able to find a single resource answering this question. I have a Comment model that can be associated with a Resource or have a parent, which is another comment. Thus allowing nested comments. A root comment is always associated with a Resource . What I am trying to achieve now is to get the hash tree of the comments that are associated with a Resource so that I can effectively get the root comments, and all the comments that is nested within a rooted comment. I am fairly new to tree structures, but I believe how I'm doing it now is not the effective (performance wise), nor the correct way to use a tree structure. resources_controller.rb def show @comments = @resource.comments.includes(:children) end resources/show.html.erb <%= comments_tree_for @comments %> comments_helper.rb def comments_tree_for(comments) comments.map do |comment| render(comment) + (comment.children.size > 0 ? content_tag(:div, comments_tree_for(comment.children), class: 'replies') : nil) end.join.html_safe end However if I run Comment.hash_tree in my console, it returns the trees. Now what I'd like to accomplish is a way to actually utilize hash_tree on my current structure. Relevant article: https://www.sitepoint.com/nested-comments-rails/ |
How to show a flash message before rendering the page while controller takes some time to process Posted: 16 Nov 2016 04:51 AM PST I am using Rails 5 and Flash. Here is a method in my controller. The query takes some 10-15 seconds to execute no matter the db tuning, due to some large volumes of data to be processed. I want to have a flash message telling something like "Processing ... " before the @result is handed over to the view with the same name to be rendered. def monthly_measurements if user_signed_in? @query = " SELECT to_char(scheduled_on, 'yyyy-mm') as year_month, get_measurements_count_by_year_month(to_char(scheduled_on, 'yyyy-mm'),NULL) as monthly_total, get_measurements_count_by_year_month(to_char(scheduled_on, 'yyyy-mm'),'Completed') as monthly_completed, get_measurements_count_by_year_month(to_char(scheduled_on, 'yyyy-mm'),'Not Completed') as monthly_not_completed FROM measurements GROUP BY year_month ORDER BY year_month DESC; " @result = Measurement.connection.execute(@query) else flash[:alert] = "Not signed in" redirect_to root_url end end |
Getting stuck with rspec 3 on windows Posted: 16 Nov 2016 05:16 AM PST I'm following a course on Coursera and I have to submit an assignment and validate it with rspec. So far I avoided all problems with rspec by simple copying the .rspec and spec folder provided with the sample code in my projects and it seems to work but now I have a spec file with following code: require 'rails_helper' feature "Module #3" do before :all do $continue = true end around :each do |example| if $continue $continue = false example.run $continue = true unless example.exception else example.skip end end #helper method to determine if Ruby class exists as a class def class_exists?(class_name) eval("defined?(#{class_name}) && #{class_name}.is_a?(Class)") == true end #helper method to determine if two files are the same def files_same?(file1, file2) if (File.size(file1) != File.size(file2)) then return false end f1 = IO.readlines(file1) f2 = IO.readlines(file2) if ((f1 - f2).size == 0) then return true else return false end end context "rq01" do context "Generate Rails application" do it "must have top level structure of a rails application" do expect(File.exists?("Gemfile")).to be(true) expect(Dir.entries(".")).to include("app", "bin", "config", "db", "lib", "public", "log", "test", "vendor") expect(Dir.entries("./app")).to include("assets", "controllers", "helpers", "mailers", "models", "views") end end end # check that TodoItem exists with fields and migration/db exists context "rq02" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end context "Scaffolding generated" do it "must have at least one controller and views" do expect(Dir.entries("./app/controllers")).to include("todo_items_controller.rb") expect(Dir.entries("./app/views/")).to include("todo_items") expect(Dir.entries("./app/views/todo_items")).to include("index.html.erb") end end context "TodoItem Model" do it "TodoItem class" do expect(class_exists?("TodoItem")) expect(TodoItem < ActiveRecord::Base).to eq(true) end end context "TodoItem class properties added" do subject(:todoItem) { TodoItem.new } it { is_expected.to respond_to(:due_date) } it { is_expected.to respond_to(:title) } it { is_expected.to respond_to(:completed) } it { is_expected.to respond_to(:description) } it { is_expected.to respond_to(:created_at) } it { is_expected.to respond_to(:updated_at) } end it "TodoItem database structure in place" do # rails g model todo_item due_date:date title description:text # rake db:migrate expect(TodoItem.column_names).to include "due_date", "title", "description", "completed" expect(TodoItem.column_types["due_date"].type).to eq :date expect(TodoItem.column_types["title"].type).to eq :string expect(TodoItem.column_types["description"].type).to eq :text expect(TodoItem.column_types["created_at"].type).to eq :datetime expect(TodoItem.column_types["updated_at"].type).to eq :datetime expect(TodoItem.column_types["completed"].type).to eq :boolean end end context "rq03" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end # Check that database has been initialized with seed file prior to test it "has the file that seeded the database" do expect(File).to exist("#{Rails.root}/db/seeds.rb") end it "must have TodoItems as provided by assignment seed file" do expect(TodoItem.all.length).to eq(3) expect(TodoItem.all.map{ |x| x.title }).to include("Task 1", "Task 2", "Task 3") end end context "rq04" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "todo_items URI should return a valid page" do visit todo_items_path expect(page.status_code).to eq(200) end end context "rq05" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" # start at main page... visit todo_items_path end scenario "Main page displays all items" do expect(page).to have_content "Task 1" expect(page).to have_content "Task 2" expect(page).to have_content "Task 3" end scenario "New action from index and create action to generate a new item" do expect(page).to have_link("New Todo item") click_link("New Todo item") expect(page).to have_content "Title" item = TodoItem.new(title:'Random', description:'', completed:true, due_date:Date.today) fill_in "Title", with: item.title select item.due_date.year, from: 'todo_item[due_date(1i)]' select item.due_date.strftime("%B"), from: 'todo_item[due_date(2i)]' select item.due_date.day, from: 'todo_item[due_date(3i)]' fill_in 'todo_item[title]', with: item.title fill_in 'todo_item[description]', with: item.description click_button 'Create Todo item' new_task = TodoItem.find_by! title: "Random" expect(TodoItem.count).to eq 4 expect(page).to have_content "Todo item was successfully created." end =begin scenario "Show link takes user to detail page about an item" do task2 = TodoItem.find_by title: "Task 2" expect(page).to have_link("Show", href: "#{todo_item_path(task2)}") click_link("Show", href: "#{todo_item_path(task2)}") expect(page).to have_content task2.due_date.strftime("%F") expect(page).to have_content task2.title expect(page).to have_content task2.description expect(page.current_path).to eq(todo_item_path(task2.id)) end scenario "Edit and update action" do new_task = TodoItem.create!(:title => "Random", :description => "", :completed => true, :due_date => Date.today) visit edit_todo_item_path(new_task) expect(page).to have_content "Description" expect(page).to have_field("Title", with: "Random") fill_in "Description", with: "fascinating" click_button "Update Todo item" new_task = TodoItem.find_by! title: "Random" expect(new_task.description).to_not be_blank expect(page).to have_content "Todo item was successfully updated." end scenario "Delete action" do new_task = TodoItem.create!(:title => "Random", :description => "", :completed => true, :due_date => Date.today) visit todo_items_path expect(page).to have_link("Destroy", href: "#{todo_item_path(new_task)}") click_link("Destroy", href: "#{todo_item_path(new_task)}") expect(TodoItem.count).to eq 3 expect(TodoItem.find_by title: "Random").to be_nil end =end end context "rq06" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "after creating an item should go to listing page" do visit new_todo_item_path fill_in "Title", with: "some title" click_button "Create Todo item" expect(page).to have_content "Listing Todo Items" expect(page.current_path).to eq(todo_items_path) end end context "rq07" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "remove edit link from listing page" do visit todo_items_path expect(page).to_not have_content('Edit') end end context "rq08" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "only display completed checkbox in the form when editing" do visit new_todo_item_path expect(page).to_not have_content('Completed') item = TodoItem.all.to_a[0] expect(item.id).to_not be_nil visit edit_todo_item_path(item.id) expect(page).to have_content('Completed') end end context "rq09" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "display somewhere on the listing page number of completed todos" do # seed the page with random items so test is specific to each run TodoItem.destroy_all numCompleted = 0; (0..15).each do |i| random_boolean = [true, false].sample if (random_boolean) then numCompleted = numCompleted + 1 end TodoItem.create!(title: "Task #{i}", due_date: Date.today, description: "description #{i}", completed: random_boolean) end visit todo_items_path expect(page).to have_content "Number of Completed Todos: #{numCompleted}" TodoItem.create! [ { title: "Task xyz", due_date: Date.today, completed: false }, { title: "Task zyx", due_date: Date.tomorrow, completed: true}, ] numCompleted = numCompleted + 1 visit todo_items_path expect(page).to have_content "Number of Completed Todos: #{numCompleted}" end end end When I run it as is with requre 'rails_helper' I get: D:/RailsInstaller/Ruby2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- rails_helper (LoadError) When I remove it I get: todolists/spec/features/module3_action_pack_spec.rb:1:in `<top (required)>': undefined method `feature' for main:Object (NoMethodError) This is my spec_helper.rb: require 'rspec' require 'capybara' require 'capybara/dsl' require 'capybara/poltergeist' RSpec.configure do |config| config.include Capybara::DSL end I tried everything I can come across on the net like downgrading to rspec 3.0.0 from 3.1.0 and changing the DirectoryMaker.rb under RailsInstaller\Ruby2.2.0\lib\ruby\gems\2.2.0\gems\rspec-support-3.5.0\lib\rspec\support as mentioned in https://github.com/rspec/rspec-support/pull/109 but I still get the error when I try to run rails generate rspec:install like this: create spec/C:/Users/Zeeshan Haider/AppData/Local/Temp/d20161116-10536-1962r60/spec/spec_helper.rb D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:252:in `mkdir': Invalid argument @ dir_s_mkdir - F:/Zeeshan Haider/Coursera/Rails with Active Record and Action Pack/todolists/spec/C: (Errno::EINVAL) from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:252:in `fu_mkdir' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:226:in `block (2 levels) in mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:224:in `reverse_each' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:224:in `block in mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:210:in `each' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:210:in `mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor/actions/create_file.rb:61:in `block in invoke!' |
Saving CART to DB RAILS Posted: 16 Nov 2016 05:49 AM PST I have a simple shop app. Users can add products to the cart (more than one). I count the TOTAL PRICE of the PRODUCTS adde by USER (logged in). My problem is how to save the cart to db with user_id, product_id and TOTAL that was counted in index.html.erb that is shown below: carts/index.html.erb <h1 align="center">Your Order</h1> <% normalPriceTotal = 0 %> <% specialPriceTotal = 0 %> <% total = 0 %> <% if @cart.empty? %> <h3 align="center" class="alert-heading"> Your order is empty</h3> <div align="center"> <%= link_to 'Order your food', products_path, class: "btn btn default btn-lg " %> </div> <% else %> <div align="center"> <%= link_to 'Empty your cart', cart_clear_path, class: "btn btn default btn-lg" %> <%= link_to 'Continue order', products_path, class: "btn btn success btn-lg" %> </div> <% end %> <% @cart.each do |id, quantity| %> <% product = Product.find_by_id(id) %> <div class="row"> <div class="col-xs-8 col-xs-offset-2"> <div class="well well-lg"> <div class="article-title"> <%= link_to product.name, product %> </div> <div class="article-meta-details"> <% if product.specialprice == nil %> <%= number_to_currency(product.price, :unit => 'PLN ') %> <% else %> <%= number_to_currency(product.specialprice, :unit => 'PLN ') %> <% end %> </div> <div class="article-meta-details"> Quantity: <%= quantity %> </div> </div> </div> </div> <% if product.specialprice != nil %> <% specialPriceTotal += quantity * product.specialprice %> <% else %> <% normalPriceTotal += quantity * product.price %> <% end %> <% total = normalPriceTotal + specialPriceTotal %> <% end %> <h3>Total price: <b><%= number_to_currency(total, :unit => 'PLN ') %> </b></h3> Here is how cart params look like: def cart_params params.require(:cart).permit(:total, :user_id, product_ids:[]) end I want to create a button that "goes" to create action in carts/controller and passes :total => total, :user_id => current_user_id, :product_ids:[product.id] |
xml to array in ruby Posted: 16 Nov 2016 06:50 AM PST I am new to ruby and rails programming and I need to parse an xml file that I get as a response and store the station names in an array. A sample of the xml is as follows : <Stations> <Station> <Code>HT</Code> <Type>knooppuntIntercitystation</Type> <Namen> <Kort>Den Bosch</Kort> <Middel>'s-Hertogenbosch</Middel> <Lang>'s-Hertogenbosch</Lang> </Namen> <Land>NL</Land> <UICCode>8400319</UICCode> <Lat>51.69048</Lat> <Lon>5.29362</Lon> <Synoniemen> <Synoniem>Hertogenbosch ('s)</Synoniem> <Synoniem>Den Bosch</Synoniem> </Synoniemen> </Station> <Station> <Code>HTO</Code> <Type>stoptreinstation</Type> <Namen> <Kort>Dn Bosch O</Kort> <Middel>Hertogenbosch O.</Middel> <Lang>'s-Hertogenbosch Oost</Lang> </Namen> <Land>NL</Land> <UICCode>8400320</UICCode> <Lat>51.700553894043</Lat> <Lon>5.3183331489563</Lon> <Synoniemen> <Synoniem>Hertogenbosch Oost ('s)</Synoniem> <Synoniem>Den Bosch Oost</Synoniem> </Synoniemen> </Station> </Stations> I need to get the Code and the Lang name in an array of hashes or just the lang name in an array. How can I do that in ruby ? thanks in advance |
input file appears to be a text format dump. Please use psql Posted: 16 Nov 2016 04:44 AM PST I take backup using pg_dump db_production > postgres_db.dump and then I copy it to localhost using scp. Now when I import on my local db it gives an error pg_restore: [archiver] input file appears to be a text format dump. Please use psql. by using commad line pg_restore -d db_development postgres_db.dump |
Undefined method `[]' for nil:NilClass in PasswordResetsController#update Posted: 16 Nov 2016 06:27 AM PST I have a problem I am trying to update-password(Reset-password). I get this error: undefined method `[]' for nil:NilClass I think the problem is in update method def create @user = User.find_by(email: params[:password_reset][:email].downcase) if @user @user.create_reset_digest @user.send_password_reset_email flash[:info] = "Email sent with password reset instructions" redirect_to root_url else flash.now[:danger] = "Email address not found" render 'new' end end def update @user = User.find_by_reset_digest(params[:id]) if params[:user][:password].empty? @user.errors.add(:password, "can't be empty") render 'edit' elsif @user.update_attributes(user_params) log_in @user flash[:success] = "Password has been reset." redirect_to @user else render 'edit' end end private def user_params params.require(:user).permit(:password, :password_confirmation) end user.rb : def create_reset_digest self.reset_token = User.new_token update_attribute(:reset_digest, User.digest(reset_token)) update_attribute(:reset_sent_at, Time.zone.now) end Please can you help me? |
No comments:
Post a Comment