acts_as_votable not working when I upvote/downvote - ruby-on-rails

I am trying to allow treatment to be votable with upvotes or downvotes but the methods provided by act_as_votable don't seem to be working as intended. When I try to display the sum of upvotes-downvotes it returns 0 each time, implying votes aren't registering like they should.
My treatments_controller.rb
def upvote
#treatment = Treatment.find(params[:id])
#treatment.upvote_by #current_user
render 'show'
end
def downvote
#treatment = Treatment.find(params[:id])
#treatment.downvote_by #current_user
redirect_to treatments_path
end
My treatment.rb
class Treatment < ActiveRecord::Base
acts_as_votable
has_many :review
has_one :service
def score
self.get_upvotes.size - self.get_downvotes.size
end
end
My routes.rb
resources :treatments do
member do
put "like", to: "treatments#upvote"
put "dislike", to: "treatments#downvote"
end
end
And my treatments/show.html.erb
<div class="container">
<div class="row">
<div class="col-sx-12 col-sm-12 col-md-8">
<h3><%= #treatment.name %></h3></br></br>
<h3>
<%= link_to "upvote", like_treatment_path(#treatment), method: :put %></br>
<%= link_to "downvote", dislike_treatment_path(#treatment), method: :put %></br>
<%= #treatment.score %></br> </h3>
The server log says the following
Started PUT "/treatments/1/like" for ::1 at 2015-12-09 16:22:14 +0000
Processing by TreatmentsController#upvote as HTML
Parameters: {"authenticity_token"=>"hQnqV+OZ6m/9kFnr5YH6j563DIjyKfA4K/8fH6kpFbXbJRbsHCcNYn1AX4usZmUNXPlnFpxHMwTM8ilFxcbdhQ==", "id"=>"1"}
Geokit is using the domain: localhost
Treatment Load (0.5ms) SELECT "treatments".* FROM "treatments" WHERE "treatments"."id" = ? LIMIT 1 [["id", 1]]
(0.5ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = ? AND "votes"."vote_scope" IS NULL [["votable_id", 1], ["votable_type", "Treatment"], ["vote_flag", "t"]]
(0.0ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = ? AND "votes"."vote_scope" IS NULL [["votable_id", 1], ["votable_type", "Treatment"], ["vote_flag", "f"]]
Rendered treatments/show.html.erb within layouts/application (6.5ms)
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
Completed 200 OK in 569ms (Views: 563.3ms | ActiveRecord: 1.0ms)

Thanks to the help of Kristjan I realised there was no insertion happening. I defined current_user within the upvote and downvote methods. The revised working versions look like so.
def upvote
current_user = User.find_by_id(session[:user_id])
#treatment = Treatment.find(params[:id])
#treatment.upvote_by current_user
render 'show'
end
def downvote
current_user = User.find_by_id(session[:user_id])
#treatment = Treatment.find(params[:id])
#treatment.downvote_by current_user
render 'show'
end

Related

Why can't I fetch images after uploading them with the Active Storage gem?

I am also using Devise. I update the seller and the avatar image doesn't appear on the sellers page. This has been going on a while.
This is the server output in the terminal:
Started GET "/farmers" for 127.0.0.1 at 2020-08-06 19:26:57 +0100
(0.5ms) SELECT sqlite_version(*)
Processing by UserController#farmers as HTML
Rendering user/farmers.html.erb within layouts/application
User Load (2.6ms) SELECT "users"."farm_name", "avatar", "users"."about_farm", "users"."farm_type", "users"."county" FROM "users" WHERE "users"."role" = ? [["role", 1]]
↳ app/views/user/farmers.html.erb:6
ActiveStorage::Attachment Load (2.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" IS NULL AND "active_storage_attachments"."record_type"
= ? AND "active_storage_attachments"."name" = ? LIMIT ? [["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
↳ app/views/user/farmers.html.erb:28
CACHE ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" IS NULL AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ? [["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
↳ app/views/user/farmers.html.erb:28
Rendered user/farmers.html.erb within layouts/application (Duration: 848.9ms | Allocations: 13223)
[Webpacker] Everything's up-to-date. Nothing to do
User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?
[["id", 18], ["LIMIT", 1]]
↳ app/views/layouts/application.html.erb:47
Rendered layouts/_search.html.erb (Duration: 1.3ms | Allocations: 173)
Completed 200 OK in 1297ms (Views: 1217.8ms | ActiveRecord: 30.9ms | Allocations: 21165)
Here is a link to the code for the view page: https://gist.github.com/Josebuendia/21ba9b9a7e6b67bf593ed44675fbb97c
And the controller that fetches the data: https://gist.github.com/Josebuendia/b22486363fdffe470b27b34daad2cc9b
user = User.last
User Load (0.8ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<User id: 18, email: "farmer12#gmail.com", created_at: "2020-08-05 16:47:08", updated_at: "2020-08-06 17:56:28", role: 1, farm_name: "Glen Valley Farm", farmers_picture: nil, about_farm: "My farm sells organic artisan beef and lamb. I'm l...", farm_type: "Mixed", county: "Wicklow">
irb(main):013:0> user.avatar.attached?
ActiveStorage::Attachment Load (3.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ?
AND "active_storage_attachments"."name" = ? LIMIT ? [["record_id", 18], ["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
=> true
irb(main):014:0>
ents" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ?
AND "active_storage_attachments"."name" = ? LIMIT ? [["record_id", 18], ["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
=> true
The weird thing is that the data is fetched correctly with the items even though that's also using the Active Storage gem!
The form elements in the items form is form.
In the other forms for the users it is f.
Though, I doubt that makes a difference.
The view page code:
<p id="notice"><%= notice %></p>
<div id="itemsContainer">
<h1>Our Farmers</h1>
<% #users.each do |user| %>
<div class="itemhols">
<%
=begin%>
<h1><%= user.email %></h1>
<%
=end%>
<!--Data to include on farmers: name, pic, about, type, county-->
<h2><%= user.farm_name %></h2>
<%
=begin%>
<p><%= image_tag user.farmers_picture if user.farmers_picture.present? %></p>
<%
=end%>
<%
=begin%>
<%= image_tag user.avatar.variant(resize: "200x200").processed if user.avatar.attached? %>
<%
=end%>
<% if user.avatar.attached? %>
<image src="<%=(url_for(user.avatar))%>" class="itemholsIm">
<% end %>
<p><%= user.about_farm %></p>
<p><%= user.farm_type %></p>
<p><%= user.county %></p>
<%
=begin%>
<%= link_to 'Show', user, :class => "button", :role => "button" %>
<%
=end%>
<%
=begin%>
<--<%= link_to 'Show', item, :class => "button", :role => "button" %>
<%
=end%>
</div>
<% end %>
</div>
And the controller that fetches the data:
class UserController < ApplicationController
def login
session[:login] = 1
session[:cart] = nil
#Changed the line below to Seller Login sucessfull! from "Admin Login sucessfull!"
flash[:notice] = "Seller Login sucessfull!"
redirect_to :controller => :items
end
def logout
session[:login] = nil
session[:cart] = nil
flash[:notice] = "You have been successfully logged out!!"
redirect_to :controller => :items
end
#iteration for farmers page
def farmers
##users = User.where(role: 1)
#users = User.select(:farm_name, :avatar, :about_farm, :farm_type, :county).where(role: 1)
end
def search
st = "%#{params[:q]}%"
#users = User.where("email like ?", st)
end
def show
end
#def farmers
# #user = User.find(params[:id])
# FIXME get the view working for the farmers page
#end
def upgrade_admin
#user.update_attribute(:adminrole, true)
redirect_to :action => :admin_users
end
def downgrade_admin
#user.update_attribute(:adminrole, false)
redirect_to :action => :admin_users
end
end
This method is most likely the culprit...although there may be other issues
def farmers
##users = User.where(role: 1)
#users = User.select(:farm_name, :avatar, :about_farm, :farm_type, :county).where(role: 1)
end
Because ActiveStorage attachments are polymorpic relationships, you need to (at the very least) include the user id in the SELECT. It also seems like, based on your wording, that it worked once but at some point stopped working. My guess is it stopped working when you commented out this line...
#users = User.where(role: 1)
I would suggest just loading the entire user to avoid future problems...
def farmers
#users = User.where(role: 1)
end
Or, add :id to the select (without :avatar)
def farmers
##users = User.where(role: 1)
#users = User.select(:id, :farm_name, :about_farm, :farm_type, :county).where(role: 1)
end
Note :avatar is not needed because it isn't actually a column in the database.

using ajax for acts_as_voteable in rails

im trying to use ajax on acts_as_votable gem so the page doesnt refresh on a vote/upvote. I've adjused the controller methods for this, and added remote true on the links. However i think the only thing left are the two .js.erb files. ive looked around on here and the ruby documentation and i cant seem to find how to do it for this instance. thanks
VM23182:1 Uncaught ReferenceError: $ is not defined
at <anonymous>:1:1
at processResponse (application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:268)
at application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:196
at XMLHttpRequest.xhr.onreadystatechange (application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:251)
`$('.unlike_post').bind('ajax:success', function(){
$(this).parent().parent().find('.vote_count').html('<%= escape_javascript #post.votes_for.size.to_s %>');
$(this).closest('.unlike_post').hide();
$(this).closest('.votes').html(' <%= link_to "Like", like_post_path(#post), remote: true, method: :get, class: "like_post" %>');
});`
Started PUT "/tweets/60/like" for 127.0.0.1 at 2018-10-02 00:06:40 +0100
Processing by TweetsController#upvote as JS
Parameters: {"id"=>"60"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ /Users/benherring/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Tweet Load (0.2ms) SELECT "tweets".* FROM "tweets" WHERE "tweets"."id" = $1 LIMIT $2 [["id", 60], ["LIMIT", 1]]
↳ app/controllers/tweets_controller.rb:57
(0.4ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = $1 AND "votes"."votable_type" = $2 AND "votes"."voter_id" = $3 AND "votes"."vote_scope" IS NULL AND "votes"."voter_type" = $4 [["votable_id", 60], ["votable_type", "Tweet"], ["voter_id", 3], ["voter_type", "User"]]
↳ app/controllers/tweets_controller.rb:58
ActsAsVotable::Vote Load (0.6ms) SELECT "votes".* FROM "votes" WHERE "votes"."votable_id" = $1 AND "votes"."votable_type" = $2 AND "votes"."voter_id" = $3 AND "votes"."vote_scope" IS NULL AND "votes"."voter_type" = $4 ORDER BY "votes"."id" DESC LIMIT $5 [["votable_id", 60], ["votable_type", "Tweet"], ["voter_id", 3], ["voter_type", "User"], ["LIMIT", 1]]
↳ app/controllers/tweets_controller.rb:58
(0.2ms) BEGIN
↳ app/controllers/tweets_controller.rb:58
ActsAsVotable::Vote Update (0.5ms) UPDATE "votes" SET "updated_at" = $1, "vote_flag" = $2 WHERE "votes"."id" = $3 [["updated_at", "2018-10-01 23:06:40.357671"], ["vote_flag", true], ["id", 10]]
↳ app/controllers/tweets_controller.rb:58
(1.3ms) COMMIT
↳ app/controllers/tweets_controller.rb:58
Rendering tweets/vote.js.erb
(0.4ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = $1 AND "votes"."votable_type" = $2 AND "votes"."vote_flag" = $3 [["votable_id", 60], ["votable_type", "Tweet"], ["vote_flag", true]]
↳ app/views/tweets/_icons.html.erb:5
(0.6ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = $1 AND "votes"."votable_type" = $2 AND "votes"."vote_flag" = $3 [["votable_id", 60], ["votable_type", "Tweet"], ["vote_flag", false]]
↳ app/views/tweets/_icons.html.erb:9
Rendered tweets/_icons.html.erb (5.7ms)
Rendered tweets/vote.js.erb (8.7ms)
Completed 200 OK in 40ms (Views: 21.0ms | ActiveRecord: 4.7ms)
resources :tweets do
member do
put "like", to: "tweets#upvote"
put "dislike", to: "tweets#downvote"
end
<div id="tweets">
<% #tweets.each do |tweet| %>
<div class="card">
<h4 class = "username"><%= link_to tweet.user.username, user_path(tweet.user) %></h4>
<p class="tweet-content"><%= tweet.content %></p>
<p class="date"><%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %></p>
<div class="icons">
<%= link_to like_tweet_path(tweet),remote: true , method: :put do %>
<div class="upvote"><i class="fas fa-thumbs-up"></i> <%= tweet.get_upvotes.size %></div>
<% end %>
<%= link_to dislike_tweet_path(tweet), remote: true, method: :put do %>
<div><i class="fas fa-thumbs-down"></i> <%= tweet.get_downvotes.size %></div>
<% end %>
</div>
</div>
<% end %>
</div>
def upvote
#tweet = Tweet.find(params[:id])
#tweet.upvote_by current_user
respond_to do |format|
format.html {redirect_to :tweets}
format.js {render layout: false}
# redirect_to :tweets
# redirect_to :tweets
# if request.xhr?
# head :ok
# else
end
end
def downvote
#tweet = Tweet.find(params[:id])
#tweet.downvote_by current_user
respond_to do |format|
format.html {redirect_to :tweets}
format.js {render layout: false}
# redirect_to :tweets
end
end
It looks like the way you initially started on is to attach handlers to the buttons that listen for successful requests. This is a fair way to do it, but - since you're already using Rails UJS - there's a possibly "better" way.
With Rails UJS, JS files returned from a remote action are automatically executed. In my opinion, a more idiomatic Rails way to do this is as follows:
Extract out the icons into their own template:
<div id="tweets">
<% #tweets.each do |tweet| %>
<div id="tweet-<%= tweet.id %>" class="card">
<h4 class = "username"><%= link_to tweet.user.username, user_path(tweet.user) %></h4>
<p class="tweet-content"><%= tweet.content %></p>
<p class="date"><%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %></p>
<%= render 'icons', tweet: tweet %>
</div>
<% end %>
</div>
tweets/_icons.html.erb:
<div class="icons">
<%= link_to like_tweet_path(tweet),remote: true , method: :put do %>
<div class="upvote"><i class="fas fa-thumbs-up"></i> <%= tweet.get_upvotes.size %></div>
<% end %>
<%= link_to dislike_tweet_path(tweet), remote: true, method: :put do %>
<div class="downvote"><i class="fas fa-thumbs-down"></i> <%= tweet.get_downvotes.size %></div>
<% end %>
</div>
Then, in your upvote/downvote controller actions you would format.js { render 'vote' } which would live at tweets/vote.js.erb and look like:
document.querySelector('#tweet-<%= #tweet.id %> .icons').outerHTML = '<%= j render('icons', tweet: #tweet) %>';
At this point, you're now free to modify tweets/_icons.html.erb to provide extra functionality (e.g. visual feedback on votes or changing the URL of the links to undo a vote).
Old jQuery method
Keeping this "older" jQuery method for those people who encounter a similar issue and are using jQuery. Though, really, you probably don't need it.
$('#tweet-<%= #tweet.id %> .icons').replaceWith('<%= j render('icons', tweet: #tweet) %>');

Error while setting up tagging for multiple models

I'm trying to setup multiple tagging in my app. I have used a single tag and tagging model which works fine for tagging a single model.
However, after setting up the association, i got this error when i wanted to create a new question undefined method map for nil:NilClass which actually points to <%= select_tag(:kategory_id, options_for_select(#kategories), :prompt => "Select Category", class: "form-control") %>. I don't know why it's pointing to this since it has nothing to do with the tagging. I might have made a mistake somewhere which i could not figure out.
Here is how i do the setup.
I added taggable_id and taggable_type to taggings table.
class AddAttributesToTaggings < ActiveRecord::Migration[5.1]
def change
add_column :taggings, :taggable_id, :integer
add_column :taggings, :taggable_type, :string
add_index :taggings, [:taggable_type, :taggable_id]
end
end
Tag.rb
class Tag < ApplicationRecord
has_many :taggings
has_many :posts, through: :taggings, source: :taggable, source_type: Post
has_many :questions, through: :taggings, source: :taggable, source_type: Question
has_many :user_tags, dependent: :destroy
has_many :users, through: :user_tags
extend FriendlyId
friendly_id :name, use: :slugged
def should_generate_new_friendly_id?
name_changed?
end
end
tagging.rb
class Tagging < ApplicationRecord
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end
Question.rb
class Question < ApplicationRecord
belongs_to :user
belongs_to :kategory
validates :title, :content, presence: true
is_impressionable counter_cache: true, unique: :all
Question.order('impressions_count DESC')
scope :most_recent, -> { order(created_at: :desc) }
extend FriendlyId
friendly_id :title, use: :slugged
def should_generate_new_friendly_id?
title_changed?
end
include Taggable
def related_questions
Question.joins(:tags).where(tags: { id: self.tags.pluck(:id) }).where.not(id: self.id)
end
end
models/concerns/taggable.rb
module Taggable
extend ActiveSupport::Concern
included do
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings
end
def tag_list
self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.friendly.find_or_create_by(name: name) }
self.tags = new_or_found_tags
end
end
tags and taggings table in schema.rb
create_table "taggings", force: :cascade do |t|
t.bigint "tag_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "taggable_id"
t.string "taggable_type"
t.index ["tag_id"], name: "index_taggings_on_tag_id"
t.index ["taggable_type", "taggable_id"], name: "index_taggings_on_taggable_type_and_taggable_id"
end
create_table "tags", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.index ["slug"], name: "index_tags_on_slug", unique: true
end
questions/_form
<%= form_with(model: question, local: true) do |form| %>
<% if question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<b><%= form.label "Category" %></b>
<%= select_tag(:kategory_id, options_for_select(#kategories), :prompt => "Select Category", class: "form-control") %>
</div>
<br>
<div class="field">
<b><%= form.label :title %></b>
<%= form.text_field :title, id: :question_title, class: "form-control" %>
</div>
<br>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content, id: :question_content, class: "form-control" %>
</div>
<br>
<div>
<%= form.label :tag_list %>
<%= form.text_field :tag_list %>
</div>
<br>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
questions_controller.rb
class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :find_contacts
before_action :find_kategory
impressionist :actions=>[:show,:index]
# GET /questions
# GET /questions.json
def index
if params[:kategory].blank?
#questions = Question.most_recent
else
#kategory_id = Kategory.find_by(name: params[:kategory]).id
#questions = Question.where(:kategory_id => #kategory_id).most_recent
end
end
# GET /questions/1
# GET /questions/1.json
def show
impressionist(#question)
#most_viewed = Question.order('impressions_count DESC').take(20)
end
# GET /questions/new
def new
#question = current_user.questions.build
#kategories = Kategory.all.map{ |k| [k.name, k.id] }
end
# GET /questions/1/edit
def edit
#kategories = Kategory.all.map{ |k| [k.name, k.id] }
end
# POST /questions
# POST /questions.json
def create
#question = current_user.questions.build(question_params)
#question.kategory_id = params[:kategory_id]
respond_to do |format|
if #question.save
flash[:success] = 'Your question was successfully posted.'
format.html { redirect_to #question }
format.json { render :show, status: :created, location: #question }
else
format.html { render :new }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
respond_to do |format|
if #question.update(question_params)
flash[:success] = 'Your question was successfully updated.'
format.html { redirect_to #question }
format.json { render :show, status: :ok, location: #question }
else
format.html { render :edit }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
#question.destroy
respond_to do |format|
flash[:success] = 'Your question has been deleted.'
format.html { redirect_to questions_url }
format.json { head :no_content }
end
end
def most_viewed
#questions = Question.order('impressions_count DESC').take(20)
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
#question = Question.friendly.includes(:tags).find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:title, :content, :kategory_id, :tag_list)
end
def find_contacts
#contacts = user_signed_in? ? current_user.all_active_contacts : ''
end
def find_kategory
#questions = Kategory.where(:kategory_id => #kategory_id)
end
end
UPDATE:**I'm now able to save a question without adding any tag but with tags added, I get a form error that tagging is invalid. **Tags are properly loaded when I edit a question.
Error Log:
Started POST "/questions" for 127.0.0.1 at 2018-07-13 12:01:01 +0100
Processing by QuestionsController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"hgLn8bzd6fVSzCIPtRd3P0Jp/LEso
/h5cKNBY0a80x3i4RF6tpLlRyqmls3xRFryqyP1/s/rLDVIt9C1/uK+qw==", "kategory_id"=>"1"
, "question"=>{"title"=>"Help!!! My Dell Inspiron 6400 is hanging", "content"=>"
Lorem ipsum dolor amet seitan offal ethical, beard viral lo-fi put a bird on it
salvia actually yr. Ethical ennui pitchfork fanny pack, gentrify seitan sartoria
l bespoke. Viral 90's church-key swag, you probably haven't heard of them banh m
i intelligentsia brunch DIY iceland wolf pitchfork. Everyday carry photo booth n
ormcore XOXO tumblr portland.\r\n\r\nBrooklyn heirloom kombucha, edison bulb leg
gings hell of DIY chartreuse austin tacos bitters. Blog hexagon copper mug blue
bottle cray. Post-ironic direct trade kale chips mumblecore. Craft beer squid cr
onut vape, hoodie bitters succulents ramps snackwave vegan small batch brunch ch
ia food truck umami. Chillwave blue bottle viral raclette authentic health goth
vape coloring book cardigan 3 wolf moon taxidermy. Gluten-free tote bag hella, l
omo pinterest direct trade gastropub tattooed. Iceland hammock post-ironic, bush
wick cornhole tumeric dreamcatcher blog palo santo chartreuse 90's food truck sy
nth chicharrones.", "tag_list"=>"hardware"}, "commit"=>"Create Question"}
User Load (2.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDE
R BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
Private::Conversation Load (2.9ms) SELECT "private_conversations".* FROM "pri
vate_conversations" WHERE ("private_conversations"."recipient_id" = $1 OR "priva
te_conversations"."sender_id" = $2) [["recipient_id", 3], ["sender_id", 3]]
Private::Message Load (2.0ms) SELECT "private_messages".* FROM "private_messa
ges" WHERE "private_messages"."conversation_id" IN (2, 3, 4, 6)
Group::Conversation Load (3.9ms) SELECT "group_conversations".* FROM "group_c
onversations" INNER JOIN "group_conversations_users" ON "group_conversations"."i
d" = "group_conversations_users"."conversation_id" WHERE "group_conversations_us
ers"."user_id" = $1 [["user_id", 3]]
Group::Message Load (2.0ms) SELECT "group_messages".* FROM "group_messages" W
HERE "group_messages"."conversation_id" = 1
User Load (2.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (2, 3,
5)
(40.0ms) SELECT "group_conversations"."id" FROM "group_conversations" INNER
JOIN "group_conversations_users" ON "group_conversations"."id" = "group_conversa
tions_users"."conversation_id" WHERE "group_conversations_users"."user_id" = $1
[["user_id", 3]]
CACHE (0.0ms) SELECT "group_conversations"."id" FROM "group_conversations" I
NNER JOIN "group_conversations_users" ON "group_conversations"."id" = "group_con
versations_users"."conversation_id" WHERE "group_conversations_users"."user_id"
= $1 [["user_id", 3]]
User Load (2.9ms) SELECT "users".* FROM "users" INNER JOIN "contacts" ON "use
rs"."id" = "contacts"."contact_id" WHERE "contacts"."user_id" = $1 AND "contacts
"."accepted" = $2 [["user_id", 3], ["accepted", "t"]]
User Load (4.9ms) SELECT "users".* FROM "users" INNER JOIN "contacts" ON "use
rs"."id" = "contacts"."user_id" WHERE "contacts"."contact_id" = $1 AND "contacts
"."accepted" = $2 ORDER BY "users"."created_at" ASC [["contact_id", 3], ["accep
ted", "t"]]
Tag Load (2.0ms) SELECT "tags".* FROM "tags" WHERE "tags"."name" = $1 LIMIT
$2 [["name", "hardware"], ["LIMIT", 1]]
Kategory Load (10.7ms) SELECT "kategories".* FROM "kategories"
(1.0ms) BEGIN
Question Exists (4.9ms) SELECT 1 AS one FROM "questions" WHERE ("questions".
"id" IS NOT NULL) AND "questions"."slug" = $1 LIMIT $2 [["slug", "help-my-dell-
inspiron-6400-is-hanging"], ["LIMIT", 1]]
Kategory Load (5.9ms) SELECT "kategories".* FROM "kategories" WHERE "kategor
ies"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.0ms) ROLLBACK
Rendering questions/new.html.erb within layouts/application
Rendered questions/_form.html.erb (17.6ms)
Rendered questions/new.html.erb within layouts/application (141.6ms)
Rendered layouts/navigation/header/_toggle_button.html.erb (1.0ms)
Rendered layouts/navigation/header/_home_button.html.erb (30.3ms)
User Load (28.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIM
IT $2 [["id", 5], ["LIMIT", 1]]
Rendered layouts/navigation/header/dropdowns/conversations/_private.html.erb (
73.2ms)
User Load (2.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMI
T $2 [["id", 3], ["LIMIT", 1]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $
1 LIMIT $2 [["id", 5], ["LIMIT", 1]]
Rendered layouts/navigation/header/dropdowns/conversations/_private.html.erb (
109.4ms)
Rendered layouts/navigation/header/dropdowns/conversations/_group.html.erb (3.
9ms)
User Load (30.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIM
IT $2 [["id", 1], ["LIMIT", 1]]
Rendered layouts/navigation/header/dropdowns/conversations/_private.html.erb (
40.0ms)
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $
1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
User Load (2.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMI
T $2 [["id", 2], ["LIMIT", 1]]
Rendered layouts/navigation/header/dropdowns/conversations/_private.html.erb (
100.6ms)
Rendered layouts/navigation/header/dropdowns/_conversations.html.erb (983.4ms)
User Load (2.0ms) SELECT "users".* FROM "users" INNER JOIN "contacts" ON "use
rs"."id" = "contacts"."user_id" WHERE "contacts"."contact_id" = $1 AND "contacts
"."accepted" = $2 [["contact_id", 3], ["accepted", "f"]]
Rendered layouts/navigation/header/dropdowns/contact_requests/_no_requests.htm
l.erb (1.0ms)
Rendered layouts/navigation/header/dropdowns/_contact_requests.html.erb (374.0
ms)
Rendered layouts/navigation/header/_dropdowns.html.erb (1713.9ms)
Rendered layouts/navigation/_header.html.erb (2485.4ms)
Kategory Load (2.9ms) SELECT "kategories".* FROM "kategories"
Rendered layouts/navigation/collapsible_elements/_constant_links.html.erb (2.0
ms)
(2.0ms) SELECT COUNT(*) FROM "questions" INNER JOIN "save_questions" ON "que
stions"."id" = "save_questions"."question_id" WHERE "save_questions"."user_id" =
$1 [["user_id", 3]]
Rendered layouts/navigation/collapsible_elements/_signed_in_links.html.erb (21
.5ms)
Rendered layouts/navigation/_collapsible_elements.html.erb (543.0ms)
Rendered layouts/_navigation.html.erb (3323.2ms)
Rendered layouts/application/_private_conversations_windows.html.erb (1.0ms)
Rendered layouts/application/_group_conversations_windows.html.erb (2.0ms)
Completed 200 OK in 22203ms (Views: 21796.6ms | ActiveRecord: 158.2ms)
You need to define #kategories = Kategory.all.map{ |k| [k.name, k.id] } in create and update actions. This actions rerender new/edit actions if they can't save the question, and they need #kategories for rerendering
If you provide the full server log for create action I can try to help you to figure out - why #question can not be saved
Looks to me like your #kategories, or something within there (perhaps a name), is nil, hence the error :) (Hopefully this is a good thing, as all may be well with your tagging.)
Ensure Kategory.all.map { |k| [k.name, k.id] } in your new action is returning records and this error should go away.
N.B. you can also use options_from_collection_for_select here.
# in the controller
def new
#question = current_user.questions.build
#kategories = Kategory.all
end
# and the view
<%= select_tag(:kategory_id, options_from_collection_for_select(#kategories, :name, :id), prompt: "Select Category", class: "form-control") %>
This way, if you don't have any categories, you won't get an error - instead, you just won't have any options available.

Rails 5 Enum With Select Field Not Saving

I understand that this has been asked many times, but for some reason none of the other solutions worked for me. I'm still unable to save a field with an enum on update.When I pass a non-enum value, like first_name, with the same form, it updates just fine, but the enum value, gender, never saves even though it shows that it is...
View:
<%= form_for(#patient, url: patient_path(params[:id])) do |f| %>
<%= f.fields_for :role do |r| %>
<%= r.fields_for :user do |u| %>
<div class="keyvalue">
<div class="key"><p>Gender</p></div>
<div class="value">
<%= u.select :gender, User.genders.map { |key, value| [key.humanize, key] }, include_blank: '-Select A Gender-' %>
</div>
<div class="push"></div>
</div><!--keyvalue-->
<% end %>
<% end %>
<% end %>
Controller:
def update
#patient = Patient.find(params[:id])
if #patient.update(patient_params)
flash[:success] = "Patient's record has been updated."
redirect_to patient_path(params[:id])
else
flash[:error] = #patient.errors.full_messages.to_sentence
redirect_to patient_path(params[:id])
end
end
Log:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"*********", "commit"=>"Update", "patient"=>{"role_attributes"=>{"user_attributes"=>{"first_name"=>"John", "middle_name"=>"Joseph", "last_name"=>"Doe", "date_of_birth"=>"1943-12-25", "gender"=>"male", "blood_type"=>"", "ethnicity"=>"", "marital_status"=>"", "id"=>"1"}, "id"=>"1"}}, "id"=>"1"}
Patient Load (0.1ms) SELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.0ms) begin transaction
Role Load (0.1ms) SELECT "roles".* FROM "roles" WHERE "roles"."roleable_id" = ? AND "roles"."roleable_type" = ? LIMIT ? [["roleable_id", 1], ["roleable_type", "Patient"], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = ? AND ("users"."id" != ?) LIMIT ? [["username", "dev"], ["id", 1], ["LIMIT", 1]]
SQL (0.3ms) UPDATE "users" SET "gender" = ?, "updated_at" = ? WHERE "users"."id" = ? [["gender", 0], ["updated_at", "2018-04-24 02:11:23.126843"], ["id", 1]]
(2.6ms) commit transaction
Redirected to http://localhost:3000/patients/1
Completed 302 Found in 10ms (ActiveRecord: 3.2ms)
Enum in User model:
enum gender: [:male, :female, :non_binary, :rather_not_say]
Migration:
t.integer :gender
The log shows no issue, it shows the gender field being updated, but if I go to the rails console it shows gender as nil

Rails Tutorial partial refresh

I went through Michael Hartl's Rails Tutorial book and I want to use Ajax for automatic feed refresh, on micropost creation and micropost deletion.
As far as I understand, I only need to specify the remote: true parameter in the form inside the correct partial and respond to js inside the appropriate method.
Nevertheless, when I try to accomplish the partial refresh with a create action I'm getting a strange NoMethodError indicating that my #feed_items is a nil object.
Started POST "/microposts" for 77.70.8.167 at 2016-06-28 10:21:32 +0000
Processing by MicropostsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qJHp9flp+EV+cxdeF69L8eSzC1fMsjr+mi57f3u3z2Y/fJI9dl1to9t4jlrX4g2uhIP67FiwvjwL7SP2Hmc4fw==", "micropost"=>{"content"=>"dsdsds"}, "commit"=>"Post"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "microposts" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["content", "dsdsds"], ["user_id", 1], ["created_at", "2016-06-28 10:21:32.797365"], ["updated_at", "2016-06-28 10:21:32.797365"]]
(11.1ms) commit transaction
###################################NilClass
Rendered shared/_feed.html.erb (7.7ms)
Rendered microposts/create.js.erb (11.5ms)
Completed 500 Internal Server Error in 43ms (ActiveRecord: 11.7ms)
NoMethodError (undefined method `any?' for nil:NilClass):
app/views/shared/_feed.html.erb:3:in `_app_views_shared__feed_html_erb___1168566426182367941_69986820092480'
app/views/microposts/create.js.erb:1:in `_app_views_microposts_create_js_erb__3336806296105309297_69986601152860'
app/controllers/microposts_controller.rb:9:in `create'
Here's my _micropost.html.erb partial:
<%= form_for(#micropost, remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new micropost..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<span class="picture">
<%= f.file_field :picture, accept: 'image/jpeg, image/gif, image/png' %>
</span>
<% end %>
<script type="text/javascript">
$('#micropost_picture').bind('change', function(){
size_in_megabytes = this.files[0].size/1024/1024;
if (size_in_megabytes > 5) {
alert('Maximum file size is 5MB. Please chose a smaller file.')
}
})
</script>
Create.js.erb:
$(".ajaxreloadposts").html("<%= escape_javascript(render('shared/feed')) %>");
_feed.html.erb:
<% if #feed_items.any? %>
<ol class="microposts">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items %>
<% end %>
Create action:
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save!
# flash[:success] = "Micropost created!"
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
else
#feed_items = []
render 'static_pages/home'
end
end
_home_logged_in.html.erb:
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= render 'shared/user_info' %>
</section>
<section class="stats">
<%= render 'shared/stats' %>
</section>
<section class="micropost_form">
<%= render 'shared/micropost_form' %>
</section>
</aside>
<div class="col-md-8">
<h3>Where are your buddies right now?</h3>
<%= render 'shared/gmaps' %>
</div>
<div class="col-md-8">
<h3>Micropost Feed</h3>
<span class="ajaxreloadposts">
<%= render 'shared/feed' %>
</span>
</div>
</div>
And finally, I guess, the relevant part of my static_pages_controller:
def home
if logged_in?
#micropost = current_user.microposts.build
#feed_items = current_user.feed.paginate(page: params[:page])
#gmaps_users = current_user.gmaps_feed
#hash = Gmaps4rails.build_markers(#gmaps_users) do |spot, marker|
marker.lat spot.lat
marker.lng spot.lng
marker.infowindow spot.user.name
end
if !current_user.checkin.nil?
#user_lat = current_user.checkin.lat
#user_lng = current_user.checkin.lng
end
end
end
I tried following these resources, but in vain:
AJAX to update micropost vote up/down partial only refreshes the most recent post
and
AJAX feed update on post
and
How to update feed using ajax in Rails 4.0
I might have missed something, but since I'm really new to Rails, I hope you'll be merciful.
Thanks for your time, help and cheers.
Okay, it might be a bit noobish, but I managed to fix the problem by inserting an instance variable called #feed_items inside both the create and destroy methods.
def create
#feed_items = current_user.feed.paginate(page: params[:page])
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save!
# flash[:success] = "Micropost created!"
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
#feed_items = current_user.feed.paginate(page: params[:page])
# flash[:success] = "Micropost deleted!"
respond_to do |format|
format.html { redirect_to request.referrer || root_url }
format.js
end
end
Here's the rails output from micropost creation and deletion:
Started POST "/microposts" for 77.70.8.167 at 2016-06-28 12:20:56 +0000
Processing by MicropostsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wd7XeH4MYDINH2+PrDy8perRJ77VKTwjZ82tsHdESbNWM6yw8Tj11KgU9otscfr6iuHWBUEruOH2DvU5EpS+qg==", "micropost"=>{"content"=>"workworkwork"}, "commit"=>"Post"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "microposts" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["content", "workworkwork"], ["user_id", 1], ["created_at", "2016-06-28 12:20:56.699428"], ["updated_at", "2016-06-28 12:20:56.699428"]]
(11.0ms) commit transaction
(3.5ms) SELECT COUNT(*) FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1)
Micropost Load (1.2ms) SELECT "microposts".* FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1) ORDER BY "microposts"."created_at" DESC LIMIT 30 OFFSET 0
CACHE...
Rendered microposts/_micropost.html.erb (43.1ms)
Rendered shared/_feed.html.erb (60.3ms)
Rendered microposts/create.js.erb (65.5ms)
Completed 200 OK in 99ms (Views: 76.4ms | ActiveRecord: 17.6ms)
Started DELETE "/microposts/348" for 77.70.8.167 at 2016-06-28 12:20:59 +0000
Processing by MicropostsController#destroy as JS
Parameters: {"id"=>"348"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Micropost Load (0.1ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? AND "microposts"."id" = ? ORDER BY "microposts"."created_at" DESC LIMIT 1 [["user_id", 1], ["id", 348]]
(0.1ms) begin transaction
SQL (0.4ms) DELETE FROM "microposts" WHERE "microposts"."id" = ? [["id", 348]]
(9.5ms) commit transaction
(0.5ms) SELECT COUNT(*) FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1)
Micropost Load (1.3ms) SELECT "microposts".* FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1) ORDER BY "microposts"."created_at" DESC LIMIT 30 OFFSET 0
CACHE...
Rendered microposts/_micropost.html.erb (50.9ms)
Rendered shared/_feed.html.erb (65.8ms)
Rendered microposts/destroy.js.erb (71.0ms)
Completed 200 OK in 99ms (Views: 75.6ms | ActiveRecord: 18.9ms)

Resources