Added a detail to Users, but value doesn't get picked up - ruby-on-rails

I added an extra field in devise when a user signs up: "barge_name", when i go to the sign up page I enter a barge_name, email address and password this all works.
But when i try rails c, User.first is says barge_name is nil, I don't know why the value doesn't get picked up when signing up? Can someone help me with this?
#<User id: 1, email: "barcelona#gmail.com", created_at: "2019-10-31 17:43:21", updated_at: "2019-10-31 17:43:21", barge_name: nil>]
schema
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "barge_name"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
migration files
class AddDetailsToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :barge_name, :string
end
end
class DeviseCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
end
end
form
<h2>Sign up</h2>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :barge_name,
required: true,
autofocus: true,
input_html: { autocomplete: "bargename" }%>
<%= f.input :email,
required: true,
autofocus: true,
input_html: { autocomplete: "email" }%>
<%= f.input :password,
required: true,
hint: ("#{#minimum_password_length} characters minimum" if #minimum_password_length),
input_html: { autocomplete: "new-password" } %>
<%= f.input :password_confirmation,
required: true,
input_html: { autocomplete: "new-password" } %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign up" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
controller
class PositionsController < ApplicationController
def new
#position = Position.new
end
def index
#positions = Position.all
end
def show
#position = Position.find(params[:id])
end
def create
#position = Position.new(position_params)
if #position.save!
redirect_to #position
PositionMailer.general_message(#position).deliver
else
render :new
end
end
private def position_params
params.require(:position).permit(:date, :time, :activity, :tripnumber)
end
end
Started POST "/users" for ::1 at 2019-11-01 18:15:31 +0100
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"K1WdKPpHZKESmfr7tZqi7yj2qM1SMIZWpXconGMbaZMZYrU1VRrpD6plMu2i79m6tWWYdAHQM98sPJzv2bDi4w==", "user"=>{"barge_name"=>"test", "email"=>"test#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameter: :barge_name

You have to add the new param like this.
application_controller.rb
before_action :configure_permitted_parameters, if: :devise_controller?
...
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:barge_name])
devise_parameter_sanitizer.permit(:account_update, keys: [:barge_name])
end
Take notice of the two lines, one is for sign_up and one is for account_update, so new and edit actions basically.

Related

Error Updating Spree User Custom Attributes

I'm attempting to add custom fields like first name, last name, avatar_url, and bio to my Spree user.
I added the fields to the table successfully:
class AddFieldsToSpreeUser < ActiveRecord::Migration[6.0]
def change
add_column :spree_users, :first_name, :string
add_column :spree_users, :last_name, :string
add_column :spree_users, :bio, :text
add_column :spree_users, :avatar_url, :string
end
end
I checked and the schema was updated according to plan:
create_table "spree_users", id: :serial, force: :cascade do |t|
t.string "encrypted_password", limit: 128
t.string "password_salt", limit: 128
t.string "email"
t.string "remember_token"
t.string "persistence_token"
t.string "reset_password_token"
t.string "perishable_token"
t.integer "sign_in_count", default: 0, null: false
t.integer "failed_attempts", default: 0, null: false
t.datetime "last_request_at"
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "login"
t.integer "ship_address_id"
t.integer "bill_address_id"
t.string "authentication_token"
t.string "unlock_token"
t.datetime "locked_at"
t.datetime "reset_password_sent_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "spree_api_key", limit: 48
t.datetime "remember_created_at"
t.datetime "deleted_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "first_name"
t.string "last_name"
t.text "bio"
t.string "avatar_url"
t.index ["bill_address_id"], name: "index_spree_users_on_bill_address_id"
t.index ["deleted_at"], name: "index_spree_users_on_deleted_at"
t.index ["email"], name: "email_idx_unique", unique: true
t.index ["ship_address_id"], name: "index_spree_users_on_ship_address_id"
t.index ["spree_api_key"], name: "index_spree_users_on_spree_api_key"
end
I added the new attributes to the Spree initializer:
Spree::PermittedAttributes.user_attributes << [:first_name]
Spree::PermittedAttributes.user_attributes << [:last_name]
Spree::PermittedAttributes.user_attributes << [:bio]
Spree::PermittedAttributes.user_attributes << [:avatar_url]
When I try to create a new user in rails c the new attributes come up as part of the model.
I have the following form to attempt to update the user:
<%= simple_form_for current_spree_user, url: spree.spree_user_registration_path(current_spree_user) do |f| %>
<%= f.object.errors.full_messages.join(", ") if f.object.errors.any? %>
<div class="row text-left">
<div class="col-sm-6 py-3">
<%= f.label "First Name" %>
<%= f.text_field :first_name, class: "form-control", required: true, autofocus: true, input_html: { autocomplete: "fname" } %>
</div> <!-- col -->
<div class="col-sm-6 py-3">
<%= f.label "Last Name" %>
<%= f.text_field :last_name, class: "form-control", input_html: { autocomplete: "lname" } %>
</div> <!-- col -->
<div class="col-12 py-3">
<%= f.label "Author Bio" %>
<%= f.text_area :bio, class: "form-control" %>
</div> <!-- col -->
<div class="col-12 py-3">
<%= f.label "Profile Image URL" %>
<%= f.text_field :avatar_url, class: "form-control", input_html: { autocomplete: "lname" } %>
</div> <!-- col -->
</div> <!-- row -->
<div class="form-actions text-center">
<%= f.button :submit, "Let's Go", class: "btn blue" %>
</div>
<% end %>
When I hit submit, I get a routing error:
ActionController::UnknownFormat
I have tried specifying method: :patch but it gets the same result. Can anyone see where I'm going wrong here?

Rails create does not save params from checkbox

I am creating a website where a user (interviewer) can create a position (a job opening).
Even if the params are sent, my create action does not save them except for the current_user.
This is what I send:
positions_controller.rb
def new
#position = Position.new
end
def create
#position = Position.new(position_params)
#position.interviewer = current_interviewer
if #position.save
redirect_to position_path(#position)
flash[:success] = "You created a new position/opening"
else
render :new
end
raise
end
private
def set_position
#position = Position.find(params[:id])
end
def position_params
params.require(:position).permit(:title, :skills, :interviewer)
end
end
_form.html.erb
<%= simple_form_for [#interviewer, #position] do |f| %>
<%= f.input :title, required:true %>
<%= f.input :skills, as: :check_boxes, collection:[
['Python', "python"],
['Java', "java"],
['JavaScript', "javascript"],
['Ruby', "ruby"],
['C++', "c++"],
['Node.js', "node"],
['React', "react"],
['Django', "django"],
['Rails', "rails"],
['SQL', "sql"],
['Doker', "doker"],
['AWS', "aws"],
['Vue.js', "vue"],
['Marketing', "Marketing"],
['HR', "hr"],
['Finance', "finance"],
['IT', "it"],
], input_html: { multiple: true } %>
<%= f.submit "Submit position", class: "btn btn-primary" %>
<% end %>
position.rb
class Position < ApplicationRecord
validates :title, presence: true
belongs_to :interviewer
end
schema
create_table "positions", force: :cascade do |t|
t.string "title"
t.bigint "interviewer_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "candidate_id"
t.string "candidatures", default: [], array: true
t.string "skills"
t.index ["candidate_id"], name: "index_positions_on_candidate_id"
t.index ["interviewer_id"], name: "index_positions_on_interviewer_id"
end
My alternative was to replace the create code with:
#position = current_interviewer.positions.new(position_params)
but it still does not work.
Since you have a input_html: { multiple: true } for the params skills, you need to add the following in positions_controller.rb:
def position_params
params.require(:position).permit(:title, :interviewer, :candidate, skills:[])
end
Basically, your skills will be saved as an array if you allow input_html: { multiple: true } for a collection
In addition, you are not passing any params for candidate
In your table, you have interviewer_id but in your permitted params you have interviewer.
Change your params to permit interviewer_id instead.
Also, in your form you have <%= f.input :title, required:true %> Presence is required by default (at least with simple_form). You don't need to declare it in the form, but you should still keep it in your Model.

Rails 4 - Unpermitted parameters for nested param despite whitelisting

I have two models user_item and user_item_images.
schema.rb
create_table "user_item_images", force: :cascade do |t|
t.integer "user_item_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "picture"
end
create_table "user_items", force: :cascade do |t|
t.integer "user_id"
t.integer "item_id"
t.integer "status", default: 0
t.boolean "hide_banner", default: false
t.datetime "created_at"
t.datetime "updated_at"
t.string "picture"
t.string "declined_reason"
end
I have a form where the user should submit a new user_item. The only field in the form is for pictures where the user can upload multiple pictures. On success, a single new user_item is created along with a new user_item_image for each picture that is uploaded.
form
<%= simple_form_for :user_item, url: user_items_path, html: {multipart: true} do |user_item_builder| %>
<%= user_item_builder.input :item_id, as: :hidden, input_html: { value: "#{#item.id}" } %>
<%= user_item_builder.simple_fields_for :user_item_images do |user_item_images_builder| %>
<%= user_item_images_builder.input :picture, as: :file, label: false, name: "user_item_images[picture][]", input_html: { multiple: true } %>
<% end %>
<% end %>
user_item_controller.rb
def create
#user_item = current_user.user_items.new(user_item_params)
raise 'foo'
if #user_item.save
params[:user_item][:user_item_images]['picture'].each do |a|
#user_item_image = #user_item.user_item_images.create!(:picture => a)
end
# Sends email to user when item request is created.
itemMailer.user_item_submission_email(current_user, #user_item.item).deliver_later
flash[:notice] = "Thank you for your item request!"
else
#user_item.errors.full_messages.each do |message|
flash[:alert] = message
end
end
redirect_to item_path(#user_item.item)
end
private
def user_item_params
params.require(:user_item).permit(:item_id, user_item_images_attributes: [:user_item_id, :picture])
end
user_item.rb
belongs_to :user
has_many :user_item_images
mount_uploader :picture, PictureUploader
accepts_nested_attributes_for :user_item_images
user_item_image.rb
mount_uploader :picture, PictureUploader
belongs_to :user_item
When I submit the form I get Unpermitted parameter: user_item_images in the console and I can't figure out why.
Change this:
<%= ..., name: "user_item_images[picture][]", ... %>
to this:
<%= ..., name: "user_item_images_attributes[picture][]", ... %>

How to .count nested_attribute boolean?

The nested attribute of quantifieds are results. In the results partial a User will checkoff if their quantified result is a :good thing or not.
In the sidebar I want to .count how many good results the User has marked off to serve as a reference point of their success.
SIDEBAR SECTION: layouts/_count.html.erb
<div class="stats">
<a href="<%= following_user_path(#user) %>">
<strong id="following" class="stat">
<%= #user.quantifieds.count %> #Works
</strong>
Quantified
</a>
<a href="<%= followers_user_path(#user) %>">
<strong id="followers" class="stat">
<%= #user.results.good.count %> #Remains zero regardless of number of checked :good boxes
</strong>
Good
</a>
</div>
quantifieds/_result_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
<br/>
<%= f.date_select :date_value, :order => [:month, :day, :year], :with_css_classes => true, :class => "modular-date-field" %>
<b><%= link_to_remove_association "Remove Result", f %></b>
<div class="america3">
<label> Good: </label>
<%= f.check_box :good %>
</div>
</div>
</div>
result.rb
class Result < ActiveRecord::Base
belongs_to :user
belongs_to :quantified
default_scope { order('date_value DESC') }
scope :good, -> { where(good: true) }
scope :bad, -> { where(good: false) }
end
Should we add a method to the application controller?
class ApplicationController < ActionController::Base
before_action :load_todays_habits
before_action :set_top_3_goals
before_action :randomize_value
before_action :set_stats
protect_from_forgery with: :exception
include SessionsHelper
def set_top_3_goals
#top_3_goals = current_user.goals.unaccomplished.top_3 if current_user
end
def randomize_value
#sidebarvaluations = current_user.valuations.randomize if current_user
end
def set_stats
#quantifieds = Quantified.joins(:results).all
#averaged_quantifieds = current_user.quantifieds.averaged if current_user
#instance_quantifieds = current_user.quantifieds.instance if current_user
end
private
def load_todays_habits
#user_tags = current_user.habits.committed_for_today.tag_counts if current_user
#all_tags = Habit.committed_for_today.tag_counts if current_user
end
# Confirms a logged-in user.
def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
end
class QuantifiedsController < ApplicationController
before_action :set_quantified, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
#quantifieds = Quantified.tagged_with(params[:tag])
else
#quantifieds = Quantified.joins(:results).all
#averaged_quantifieds = current_user.quantifieds.averaged
#instance_quantifieds = current_user.quantifieds.instance
end
end
def show
end
def new
#quantified = current_user.quantifieds.build
end
def edit
end
def create
#quantified = current_user.quantifieds.build(quantified_params)
if #quantified.save
redirect_to quantifieds_url, notice: 'Quantified was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
def update
if #quantified.update(quantified_params)
redirect_to quantifieds_url, notice: 'Goal was successfully updated'
else
render action: 'edit'
end
end
def destroy
#quantified.destroy
redirect_to quantifieds_url
end
private
def set_quantified
#quantified = Quantified.find(params[:id])
end
def correct_user
#quantified = current_user.quantifieds.find_by(id: params[:id])
redirect_to quantifieds_path, notice: "Not authorized to edit this goal" if #quantified.nil?
end
def quantified_params
params.require(:quantified).permit(:categories, :metric, :result, :date, :comment, :private_submit, :tag_list, :good, results_attributes: [:id, :result_value, :date_value, :good, :_destroy])
end
end
quantifieds/_form
<%= javascript_include_tag "quantified.js" %>
<%= simple_form_for(#quantified) do |f| %>
<%= f.error_notification %>
<div class="america">
<form>
<% Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:categories, c, :class => "date-format-switcher") %>
<%= label(c, c) %>
<% end %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :tag_list, quantified: #quantified.tag_list.to_s.titleize, class: 'form-control', placeholder: 'Enter Action' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<b><%= link_to_add_association 'Add Result', f, :results %></b>
</div>
<div class="america2">
<%= button_tag(type: 'submit', class: "btn") do %>
<span class="glyphicon glyphicon-plus"></span>
<% end %>
<%= link_to quantifieds_path, class: 'btn' do %>
<span class="glyphicon glyphicon-chevron-left"></span>
<% end %>
<%= link_to #quantified, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn' do %>
<span class="glyphicon glyphicon-trash"></span>
<% end %>
</div>
<label> Private: </label>
<%= f.check_box :private_submit %>
</form>
</div>
<% end %>
quantifieds.rb
class Quantified < ActiveRecord::Base
belongs_to :user
has_many :results #correct
has_many :comments, as: :commentable
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true #correct
scope :averaged, -> { where(categories: 'Averaged') }
scope :instance, -> { where(categories: 'Instance') }
scope :private_submit, -> { where(private_submit: true) }
scope :public_submit, -> { where(private_submit: false) }
validates :categories, :metric, presence: true
acts_as_taggable
CATEGORIES = ['Averaged', 'Instance']
end
schema.rb
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150317171422) do
create_table "activities", force: true do |t|
t.integer "trackable_id"
t.string "trackable_type"
t.integer "owner_id"
t.string "owner_type"
t.string "key"
t.text "parameters"
t.integer "recipient_id"
t.string "recipient_type"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "activities", ["owner_id", "owner_type"], name: "index_activities_on_owner_id_and_owner_type"
add_index "activities", ["recipient_id", "recipient_type"], name: "index_activities_on_recipient_id_and_recipient_type"
add_index "activities", ["trackable_id", "trackable_type"], name: "index_activities_on_trackable_id_and_trackable_type"
create_table "comments", force: true do |t|
t.text "content"
t.integer "commentable_id"
t.string "commentable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["commentable_id", "commentable_type"], name: "index_comments_on_commentable_id_and_commentable_type"
create_table "days", force: true do |t|
t.integer "level_id"
t.integer "habit_id"
t.boolean "missed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "goals", force: true do |t|
t.string "name"
t.date "deadline"
t.boolean "accomplished"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "goals", ["user_id", "created_at"], name: "index_goals_on_user_id_and_created_at"
add_index "goals", ["user_id"], name: "index_goals_on_user_id"
create_table "habits", force: true do |t|
t.datetime "left"
t.integer "level"
t.text "committed"
t.datetime "date_started"
t.string "trigger"
t.string "target"
t.string "reward"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "habits", ["user_id", "created_at"], name: "index_habits_on_user_id_and_created_at"
add_index "habits", ["user_id"], name: "index_habits_on_user_id"
create_table "levels", force: true do |t|
t.integer "user_id"
t.integer "habit_id"
t.boolean "passed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "quantifieds", force: true do |t|
t.string "categories"
t.string "metric"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "quantifieds", ["user_id", "created_at"], name: "index_quantifieds_on_user_id_and_created_at"
add_index "quantifieds", ["user_id"], name: "index_quantifieds_on_user_id"
create_table "relationships", force: true do |t|
t.integer "follower_id"
t.integer "followed_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "relationships", ["followed_id"], name: "index_relationships_on_followed_id"
add_index "relationships", ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
add_index "relationships", ["follower_id"], name: "index_relationships_on_follower_id"
create_table "results", force: true do |t|
t.integer "user_id"
t.string "result_value"
t.date "date_value"
t.integer "quantified_id"
t.boolean "good"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "taggings", force: true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context", limit: 128
t.datetime "created_at"
end
add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", force: true do |t|
t.string "name"
t.integer "taggings_count", default: 0
end
add_index "tags", ["name"], name: "index_tags_on_name", unique: true
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.text "missed_days"
t.text "missed_levels"
t.string "provider"
t.string "uid"
t.string "oauth_token"
t.datetime "oauth_expires_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
create_table "valuations", force: true do |t|
t.string "name"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "valuations", ["user_id", "created_at"], name: "index_valuations_on_user_id_and_created_at"
add_index "valuations", ["user_id"], name: "index_valuations_on_user_id"
end
class User < ActiveRecord::Base
has_many :authentications
has_many :habits, dependent: :destroy
has_many :levels
has_many :valuations, dependent: :destroy
has_many :comments, as: :commentable
has_many :goals, dependent: :destroy
has_many :quantifieds, dependent: :destroy
has_many :results, dependent: :destroy
Thanks so much for your time!
You can update your Result as follows:
class Result < ActiveRecord::Base
# rest of the code
scope :good, -> { where(good: true) }
scope :good_count, -> { good.count }
end
Let's perform some tests in rails console:
u = User.create({ user_attributes })
u.results.create(good: true)
u.results.create(good: false)
u.results.create(good: true)
u.results.count
# => SELECT COUNT(*) FROM "results" WHERE "results"."user_id" = ? [["user_id", 1]]
# => 3
u.results.good_count
# => SELECT COUNT(*) FROM "results" WHERE "results"."user_id" = ? AND "results"."good" = 't' [["user_id", 1]]
# => 2
If you changed your User as follows:
class User < ActiveRecord::Base
# rest of the code
def good_results_count
results.good_count
end
end
which is much cleaner solution, you can use it in your application like:
# assuming we have data set like in previous step
u = User.last
u.good_results_count # you can use this line in your template
# => SELECT COUNT(*) FROM "results" WHERE "results"."user_id" = ? AND "results"."good" = 't' [["user_id", 1]]
# => 2
If, for some reason, the value remains 0 - as you mentioned - try performing the operations I described in console to see real data in database. Maybe this is not the problem with fetching proper data, maybe data is not saved correctly?
Let me know how it goes, so we're try to address the real problem!
Good luck!
Update
Problem in view is due to lack of proper association between User and Result. What currently is in User:
class User < ActiveRecord::Base
# rest of the code
has_many :quantifieds, dependent: :destroy
has_many :results, dependent: :destroy
# rest of the code
end
When new Results are created through Quantifieds, this is what you have in QuantifiedsController#create:
class QuantifiedsController < ApplicationController
def create
#quantified = current_user.quantifieds.build(quantified_params)
if #quantified.save
redirect_to quantifieds_url, notice: 'Quantified was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
end
Well, everything looks perfectly all right, but the problem is actually in line #quantified = current_user.quantifieds.build(quantified_params). All Results created this was have user_id = nil, only the quantified_id is set properly.
How to fix this?
By simplifying the associations! There is no need to store both quantify_id and user_id in Result.
If there is a relation like: User has many Quantifies, and Quantify has many Results, you can quite easily access Results of Users by proper declaration in User:
class User < ActiveRecord::Base
# rest of the code
has_many :quantifieds, dependent: :destroy
has_many :results, through: :quantifieds
# rest of the code
end
This is quite clever thing! Let's see, what happens under the hood:
u = User.last
u.results
Result Load (0.3ms) SELECT "results".* FROM "results" INNER JOIN "quantifieds" ON "results"."quantified_id" = "quantifieds"."id" WHERE "quantifieds"."user_id" = ? ORDER BY date_value DESC [["user_id", 5]]
=> #<ActiveRecord::Associations::CollectionProxy ...>
Now, when relation is set up as described above, the proper counts should appear in website.
There is no need to store user_id in Result, so you can freely remove it!
<div class="stats">
<a href="<%= following_user_path(#jadenmcgruder) %>">
<strong id="following" class="stat">
<%= #jadenmcgruder.quantifieds.count %> #Works
</strong>
Quantified
</a>
<a href="<%= followers_user _path(#jadenmcgruder) %>">
<strong id="followers" class="stat">
<%= #jadenmcgruder.results.good.count %> #Remains zero regardless of number of checked :good boxes
</strong>
Good
</a>
</div>

adding row to table through form

I am trying to create a form that will add a row to my table but I am getting this error and I am not sure why:
Started POST "/test" for ::1 at 2014-11-30 01:51:49 -0800
Processing by UsersController#create as JS
Parameters: {"utf8"=>"✓", "users"=>{"first_name"=>"brady", "last_name"=>"LIII", "email"=>"brad#gmail.com", "phone_number"=>"123456789"}, "commit"=>"Save Users"}
Completed 500 Internal Server Error in 1ms
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/users_controller.rb:32:in `create'
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_source.erb (2.0ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_trace.text.erb (0.9ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/_request_and_response.text.erb (0.5ms)
Rendered /Users/bli1/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0.beta4/lib/action_dispatch/templates/rescues/diagnostics.text.erb (11.5ms)
::1 - - [30/Nov/2014:01:51:49 -0800] "POST /test HTTP/1.1" 500 92618 0.0449
My form:
<!-- contact -->
<section id="contact">
<div class="container">
<div class="title-container">Contact Us</div>
<div class="title-caption">Reach us at (415)-911-9999</div>
<%= form_for(:users, remote: true, id: "contact-form", class: "contact-input") do |f| %>
<div class="col-md-12">
<div class="col-md-6">
<div class="contact-input-margin form-group">
<%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>
</div>
<div class="contact-input-margin form-group">
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>
</div>
<div class="contact-input-margin form-group">
<%= f.email_field(:email, class: "form-control", placeholder: "Email") %>
</div>
<div class="contact-input-margin form-group">
<%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>
</div>
</div>
</div>
<%= f.submit(class: "btn btn-xl") %>
<% end %>
</div>
</section>
My controller:
class UsersController < ApplicationController
def new
end
def create
if !(User.find_by(email: params[:user][:email]))
#user = User.new(user_params)
#user.save
end
end
private
def user_params
params.require(:users).permit(:first_name, :last_name, :email, :phone_number)
end
end
my user model
class User < ActiveRecord::Base
before_save { |user| user.email = user.email.downcase }
has_many :contact_requests
validates(:first_name, presence: true)
validates(:last_name, presence: true)
validates(:email, presence: true)
accepts_nested_attributes_for :contact_requests
end
my routes
Rails.application.routes.draw do
root 'home#index'
get 'test', to: "users#new"
post 'test', to: "users#create"
schema:
ActiveRecord::Schema.define(version: 20141130075753) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "contact_requests", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "message", null: false
t.integer "user_id"
end
add_index "contact_requests", ["user_id"], name: "index_contact_requests_on_user_id", using: :btree
create_table "users", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name", null: false
t.string "last_name", null: false
t.string "email", null: false
t.string "phone_number"
end
end

Resources