Rails 5 Enum With Select Field Not Saving - ruby-on-rails

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

Related

Ajax in Rails 5 throw "ActionController::UnknownFormat " error

I am trying to implement a search method that will automaticaly populate a form through the use of Ajax.
I have a simple_form_form that is feed with a collection of Client instance. Once I select a client, a js code submit the form and then goes to the corresponded controller method.
This part is working, but when the code hits the Client#search it stops at my "respond_to |format|" line. Stating that this is an unknown format.
I looked differents stackover posts, but I could'nt find any concrete answers.
Thanks,
here is the code:
My error:
error messages
routes.rb
Rails.application.routes.draw do
class OnlyAjaxRequest
def matches?(request)
request.xhr?
# raise
end
end
get 'search', to: 'invoices#search', as: 'search', constraint: OnlyAjaxRequest.new
end
formSubmit.js
let clientOption = document.querySelector('#search_client');
const form = document.querySelector('.search');
clientOption.addEventListener('change', (event) => {
form.submit();
})
Client Controller:
def search
if params[:search]
#client_found = Client.find(params[:search][:client]) if Client.find(params[:search][:client]).present?
respond_to do |format|
#format.html {}
format.js { render :search}
end
end
end
Search.js.erb
console.log('hello');
$('#ajx-cli').html("<%= escape_javascript(render partial: 'invoices/invoice_new_partial/find_client')%>");
Client Selection Form
<%= simple_form_for :search, url: search_path, remote: true, method: :get, html: { id: :find_cli } do |f| %>
<%= f.input :client, label:"Sélectionnez un client", collection: #my_clients, label_method: :company_name, value_method: :id, include_blank: true, as: :select %>
<% end %>
Updated Form
<div id='ajx-cli'>
<%= f.fields_for :client do |client| %>
<%= render partial: "invoices/invoice_new_partial/oneoff_client",locals: {f: client, client_found: #client_found} %>
<% end %>
</div>
Also, my search action seems to be processed as html instead of js.
Logs terminal
Started GET "/search?utf8=%E2%9C%93&search%5Bclient%5D=176" for ::1 at 2020-10-17 14:15:07 +0200
Processing by InvoicesController#search as HTML
Parameters: {"utf8"=>"✓", "search"=>{"client"=>"176"}}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 92], ["LIMIT", 1]]
↳ /Users/utilisateur/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Invoice Exists (0.7ms) SELECT 1 AS one FROM "invoices" WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 LIMIT $2 [["status", 3], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:32
Invoice Update All (0.9ms) UPDATE "invoices" SET "status" = 4 WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 [["status", 3]]
↳ app/controllers/application_controller.rb:34
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 176], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
CACHE Client Load (0.0ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 176], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
Completed 406 Not Acceptable in 9ms (ActiveRecord: 2.3ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/invoices_controller.rb:58:in `search'
EDIT
Trying to force format didn't work either. My request was correctly processed as JS, so I didn't have the same error, but my search.js.erb was rendered instead of being executed.
New Invoice#search
def search
if params[:search]
#client_found = Client.find(params[:search][:client]) if Client.find(params[:search][:client]).present?
respond_to do |format|
format.js { render layout: false, content_type: 'text/javascript'}
end
end
New Client Selection Form
<%= simple_form_for :search, url: search_path(format: :js), remote: true, method: :get, html: { id: :find_cli } do |f| %>
<%= render partial: "invoices/invoice_new_partial/client_selection",locals: {my_clients: #my_clients, f: f, client_found: #client_found} %>
<% end %>
Logs:
Started GET "/search.js?utf8=%E2%9C%93&search%5Bclient%5D=178" for ::1 at 2020-10-17 19:19:43 +0200
Processing by InvoicesController#search as JS
Parameters: {"utf8"=>"✓", "search"=>{"client"=>"178"}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 92], ["LIMIT", 1]]
↳ /Users/utilisateur/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Invoice Exists (0.6ms) SELECT 1 AS one FROM "invoices" WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 LIMIT $2 [["status", 3], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:32
Invoice Update All (6.5ms) UPDATE "invoices" SET "status" = 4 WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 [["status", 3]]
↳ app/controllers/application_controller.rb:34
Client Load (0.3ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 178], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
CACHE Client Load (0.1ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 178], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
Rendering invoices/search.js.erb
Rendered invoices/invoice_new_partial/_find_client.html.erb (0.5ms)
Rendered invoices/search.js.erb (2.2ms)
Completed 200 OK in 24ms (Views: 5.6ms | ActiveRecord: 7.9ms)
I couldn't wrapped my mind around why my js.erb was rendered as a plain text, instead of being executed, so I started over.
I updated my form Submit.js and it worked like a charm.
New routes.rb
post 'search', to: 'invoices#search', as: 'search'
New Client Selection form
<%= simple_form_for :search, remote: true, html: { id: :find_cli } do |f| %>
<%= render partial: "invoices/invoice_new_partial/client_selection",locals: {my_clients: #my_clients, f: f, client_found: #client_found} %>
<% end %>
New formSubmit.js
let clientOption = document.querySelector('#search_client');
const form = document.querySelector('.search');
clientOption.addEventListener('change', (event) => {
let selector = document.querySelector('#search_client')
let client = selector.options[selector.selectedIndex].value;
Rails.ajax({
type: "post",
url: `/search?utf8=✓&search%5Bclient%5D=${client}`,
headers: {
accept: '*/*',
'X-CSRF-Token': Rails.csrfToken()
}
});
});

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.

Images not uploading in Database Rails 5 | Paperclip

I'm unable to upload an image in my nested scaffold form.
All other fields are getting in the database except the image. Please help!
I am on rails 5.2 and using paperclip for image uploading and images need to be uploaded on AWS.
I am not getting any errors its just the images are not entering the database.
Thanks!
Controller
class ContentsController < ApplicationController
before_action :set_campaign, except: [:your_posts]
before_action :set_content, only: [:show, :edit, :update, :destroy, :approve, :decline]
# GET campaigns/1/contents
def index
#contents = #campaign.contents
end
# GET campaigns/1/contents/1
def show
end
# GET campaigns/1/contents/new
def new
#content = #campaign.contents.build
end
# GET campaigns/1/contents/1/edit
def edit
end
# POST campaigns/1/contents
def create
if !current_user.is_active_influencer
return redirect_to payout_method_path, alert: "Please Connect to Stripe Express first."
end
campaign = Campaign.find(params[:campaign_id])
if campaign.active == false
flash[:alert] = "This Campaign is closed"
elsif current_user == campaign.user
flash[:alert] = "You cannot apply for your own campaign!"
elsif
#content = current_user.contents.build(content_params)
#content.campaign = campaign
#content.transaction_fee = #content.price * 15/100
#content.total = #content.price + #content.transaction_fee
#content.save
flash[:notice] = "Applied Successfully!"
end
redirect_to campaign
end
# PUT campaigns/1/contents/1
def update
if #content.update_attributes(content_params)
redirect_to([#content.campaign, #content], notice: 'Content was successfully updated.')
else
render action: 'edit'
end
end
# DELETE campaigns/1/contents/1
def destroy
#content.destroy
redirect_to campaign_contents_url(#campaign)
end
def your_posts
#posts = current_user.contents
end
def approve
if current_user.stripe_id.blank?
flash[:alert] = "Please update your payment method."
return redirect_to payment_method_path
elsif
charge(#campaign, #content)
elsif
flash[:alert] = "Cannot make a reservation!"
end
end
def decline
#content.Declined!
redirect_to campaign_contents_path
end
private
#Twilio_start
def send_sms(campaign, content)
#client = Twilio::REST::Client.new
#client.messages.create(
from: '+18646060816',
to: content.user.phone_number,
body: "You content for '#{campaign.brand_name}' has been approved."
)
end
#Twilio_end
def charge(campaign, content)
if !campaign.user.stripe_id.blank?
customer = Stripe::Customer.retrieve(campaign.user.stripe_id)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => content.total * 100,
:description => campaign.name,
:currency => "usd",
:destination => {
:amount => content.price * 95, # 95% of the content amount goes to the Content Maker
:account => content.user.merchant_id # Influencer's Stripe customer ID
}
)
if charge
content.Approved!
ContentMailer.send_email_to_influencer(content.user, campaign).deliver_later if content.user.setting.enable_email
send_sms(campaign, content) if content.user.setting.enable_sms #Twilio
flash[:notice] = "Paid and Approved successfully!"
redirect_to campaign_contents_path
else
reservation.Declined!
flash[:alert] = "Cannot charge with this payment method!"
end
end
rescue Stripe::CardError => e
content.Declined!
flash[:alert] = e.message
end
# Use callbacks to share common setup or constraints between actions.
def set_campaign
#campaign = Campaign.find(params[:campaign_id])
end
def set_content
#content = #campaign.contents.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def content_params
params.require(:content).permit(:post_copy, :is_facebook, :is_instagram, :is_twitter, :is_youtube, :price, :images)
end
end
Model
class Content < ApplicationRecord
enum status: {Waiting: 0, Approved: 1, Declined: 2}
after_create_commit :create_notification
belongs_to :user
belongs_to :campaign
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
private
def create_notification
type = self.campaign.Instant? ? "New Booking" : "New Request"
influencer = User.find(self.user_id)
Notification.create(content: "#{type} from #{influencer.fullname}", user_id: self.campaign.user_id)
end
end
Views
<div class="panel panel-default">
<div class="panel-heading">
<span><i class="fa fa-bolt" style="color: #ffb400"></i> Apply for this campaign</span>
</div>
<div class="panel-body">
<%= form_for([#campaign, #campaign.contents.new]) do |f| %>
<div class="row">
<div class="col-md-12">
<label>Post Copy</label>
<%= f.text_area :post_copy, rows: 5, placeholder: "Create your post exactly as you'd like to see it published.", class: "form-control", required: true %>
</div>
</div>
<div class="row">
<div class="col-md-12">
<label>Price USD</label>
<%= f.text_field :price, placeholder: "How much you will charge", class: "form-control", required: true %>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span class="btn btn-default btn-file text-babu">
<i class="fa fa-cloud-upload" aria-hidden="true"></i> Select Photos
<%= f.file_field "images[]", type: :file, multiple: true %>
</span>
</div>
</div>
<div class="row">
<div class="col-md-12">
<label>Where will you post?</label>
</div>
<% if !#campaign.facebook.blank? %>
<div class="col-md-3">
<%= f.check_box :is_facebook %> Facebook
</div>
<% end %>
<% if !#campaign.twitter.blank? %>
<div class="col-md-3">
<%= f.check_box :is_twitter %> Twitter
</div>
<% end %>
<% if !#campaign.instagram.blank? %>
<div class="col-md-3">
<%= f.check_box :is_instagram %> Instagram
</div>
<% end %>
<% if !#campaign.youtube.blank? %>
<div class="col-md-3">
<%= f.check_box :is_youtube %> Youtube
</div>
<% end %>
</div>
<br/>
<%= f.submit "Submit for Approval", class: "btn btn-normal btn-block" %>
<% end %>
</div>
</div>
Terminal Response
Started POST "/campaigns/1/contents" for 127.0.0.1 at 2018-10-18 12:46:35 +0530
Processing by ContentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SavnYHjl5BHdUQXu4hVeyKHGgTgz7bfxXavDG8mKO2S1W0vfvjDn9RptHGJSBin/a0Gc2b7AfgzLY2eq2OpIRA==", "content"=>{"post_copy"=>"Test 5", "price"=>"10", "images"=>[], "is_facebook"=>"1", "is_instagram"=>"1"}, "commit"=>"Submit for Approval", "campaign_id"=>"1"}
Campaign Load (0.3ms) SELECT "campaigns".* FROM "campaigns" WHERE "campaigns"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/contents_controller.rb:126
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/controllers/contents_controller.rb:25
CACHE Campaign Load (0.0ms) SELECT "campaigns".* FROM "campaigns" WHERE "campaigns"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/contents_controller.rb:29
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/contents_controller.rb:32
Unpermitted parameter: :images
(0.1ms) begin transaction
↳ app/controllers/contents_controller.rb:39
Content Create (3.2ms) INSERT INTO "contents" ("user_id", "campaign_id", "post_copy", "is_facebook", "is_instagram", "price", "transaction_fee", "total", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["user_id", 2], ["campaign_id", 1], ["post_copy", "Test 5"], ["is_facebook", 1], ["is_instagram", 1], ["price", 10], ["transaction_fee", 1], ["total", 11], ["created_at", "2018-10-18 07:16:35.409569"], ["updated_at", "2018-10-18 07:16:35.409569"]]
↳ app/controllers/contents_controller.rb:39
(11.4ms) commit transaction
↳ app/controllers/contents_controller.rb:39
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/models/content.rb:16
(0.1ms) begin transaction
↳ app/models/content.rb:18
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/models/content.rb:18
Notification Create (0.8ms) INSERT INTO "notifications" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["content", "New Request from Influencer"], ["user_id", 1], ["created_at", "2018-10-18 07:16:35.443967"], ["updated_at", "2018-10-18 07:16:35.443967"]]
↳ app/models/content.rb:18
(3.1ms) commit transaction
↳ app/models/content.rb:18
[ActiveJob] Enqueued NotificationJob (Job ID: dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5) to Async(default) with arguments: #<GlobalID:0x00007fbe15387ec8 #uri=#<URI::GID gid://Notification/5>>
Redirected to http://localhost:3000/campaigns/1
Completed 302 Found in 60ms (ActiveRecord: 20.1ms)
Notification Load (0.7ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
↳ /Users/peeyushverma/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] Performing NotificationJob (Job ID: dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5) from Async(default) with arguments: #<GlobalID:0x00007fbe15346478 #uri=#<URI::GID gid://Notification/5>>
Started GET "/campaigns/1" for 127.0.0.1 at 2018-10-18 12:46:35 +0530
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] ↳ app/jobs/notification_job.rb:5
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] User Update All (1.8ms) UPDATE "users" SET "unread" = COALESCE("unread", 0) + 1 WHERE "users"."id" = ? [["id", 1]]
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] ↳ app/jobs/notification_job.rb:5
Processing by CampaignsController#show as HTML
Parameters: {"id"=>"1"}
Campaign Load (7.5ms) SELECT "campaigns".* FROM "campaigns" WHERE "campaigns"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] Rendered notifications/_notification.html.erb (1.7ms)
↳ app/controllers/campaigns_controller.rb:69
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] [ActionCable] Broadcasting to notification_1: {:message=>"<div class=\"panel\">\n <div class=\"panel-body\">\n <strong>New Request from Influencer</strong>\n <span class=\"pull-right\">18 Oct 07:16</span>\n </div>\n</div>\n", :unread=>2}
[ActiveJob] [NotificationJob] [dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5] Performed NotificationJob (Job ID: dd4f41ce-9428-49b5-9d29-8ec67c2bb4a5) from Async(default) in 76.89ms
NotificationsChannel transmitting {"message"=>"<div class=\"panel\">\n <div class=\"panel-body\">\n <strong>New Request from Influencer</strong>\n <span class=\"pull-right\">18 Oct 07:16</span>\n </div>\n</div>\n", "unread"=>2} (via streamed from notification_1)
Rendering campaigns/show.html.erb within layouts/application
Photo Load (1.1ms) SELECT "photos".* FROM "photos" WHERE "photos"."campaign_id" = ? [["campaign_id", 1]]
↳ app/models/campaign.rb:19
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/views/campaigns/show.html.erb:20
Campaign Load (0.8ms) SELECT campaigns.*, (111.19492664455873 * ABS(campaigns.latitude - 22.3511148) * 0.7071067811865475) + (96.29763124613503 * ABS(campaigns.longitude - 78.6677428) * 0.7071067811865475) AS distance, CASE WHEN (campaigns.latitude >= 22.3511148 AND campaigns.longitude >= 78.6677428) THEN 45.0 WHEN (campaigns.latitude < 22.3511148 AND campaigns.longitude >= 78.6677428) THEN 135.0 WHEN (campaigns.latitude < 22.3511148 AND campaigns.longitude < 78.6677428) THEN 225.0 WHEN (campaigns.latitude >= 22.3511148 AND campaigns.longitude < 78.6677428) THEN 315.0 END AS bearing FROM "campaigns" WHERE (campaigns.latitude BETWEEN 22.26118263940813 AND 22.441046960591873 AND campaigns.longitude BETWEEN 78.57050526395783 AND 78.76498033604217 AND campaigns.id != 1) ORDER BY distance ASC LIMIT ? [["LIMIT", 3]]
↳ app/views/campaigns/show.html.erb:149
Rendered contents/_form.html.erb (7.1ms)
Rendered campaigns/show.html.erb within layouts/application (32.6ms)
Rendered shared/_message.html.erb (1.2ms)
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/views/shared/_navbar.html.erb:23
Rendered shared/_navbar.html.erb (7.9ms)
Completed 200 OK in 378ms (Views: 326.5ms | ActiveRecord: 10.6ms)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2018-10-18 12:46:35 +0530
MessagesChannel stopped streaming from conversation_
NotificationsChannel stopped streaming from notification_2
Started GET "/cable" for 127.0.0.1 at 2018-10-18 12:46:36 +0530
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2018-10-18 12:46:36 +0530
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
MessagesChannel is transmitting the subscription confirmation
MessagesChannel is streaming from conversation_
NotificationsChannel is transmitting the subscription confirmation
NotificationsChannel is streaming from notification_2
in your model, you have:
has_attached_file :image
So I am assuming, Every Content has only one Image attached with it, but in you form in views, you are uploading multiple images as an array.
<%= f.file_field "images[]", type: :file, multiple: true %>
Change this to:
<%= f.file_field :image %>
Also, in you ContentController, in content_params action, change :images param to :image
params.require(:content).permit(:post_copy, :is_facebook, :is_instagram, :is_twitter, :is_youtube, :price, :image)
But, if you want attach multiple images then you have to change the approach entirely.
To have paperclip supported uploading to s3, you need to add gem "aws-sdk-s3" to Gemfile file? And set s3_credentials in model
class Content < ApplicationRecord
#
# rest of codes
###
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" } ,
:storage => :s3,
:s3_credentials => {
:bucket => "xxx",
:access_key_id => "xxx",
:secret_access_key => "xxx"}
#rest of code
end
FYI https://www.rubydoc.info/gems/paperclip/Paperclip/Storage/S3

param is missing or the value is empty: purchase

I'm trying to pass the following inside a def create method. The create method is in the transactions controller.
#purchases = current_shop.purchases.build(purchase_params)
#purchases.save!
private
def purchase_params
params.require(:purchase).permit(:shop_id, :subscription_id, :created_at)
end
And returns this error:
ActionController::ParameterMissing in TransactionsController#create
param is missing or the value is empty: purchase
Update 1
Logs:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"aJWUUEwgtG0o52MEHSOcNETj1Ueo+4NvLBD+y5LMPHxtHnOEe1Zgs3IMADdv5y+dbl7Ecgr8LMEjIG6sws9kqg==", "payment_method_nonce"=>"bf7458d2-d3a4-02c9-2593-526174f50822"}
Cart Load (0.1ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT ? [["id", 93], ["LIMIT", 1]]
Shop Load (0.3ms) SELECT "shops".* FROM "shops" WHERE "shops"."id" = ? ORDER BY "shops"."id" ASC LIMIT ? [["id", 13], ["LIMIT", 1]]
LineItem Load (0.4ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ? [["cart_id", 93]]
Subscription Load (0.1ms) SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
Completed 400 Bad Request in 2899ms (ActiveRecord: 1.1ms)
ActionController::ParameterMissing (param is missing or the value is empty: purchase):
app/controllers/transactions_controller.rb:60:in purchase_params'
app/controllers/transactions_controller.rb:31:in create'
Update 2
<p id="notice"><%= notice %></p>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<div class="form-container radius-box glassy-bg small-10 small-centered medium-8 large-6 columns">
<h2 class="mbs">New Transaction</h2>
<%= form_tag transactions_path do%>
<p>Please enter your payment details:</p>
<div id="dropin"></div>
<%=submit_tag "Pay #{#cart.total_price}$", class: "button mt1" %>
<%end%>
</div>

Rails - Name can't be blank error when the input isn't blank

I get an error of 'Name can't be blank' and "Name only allows letters, numbers and '-'" when trying to update a name. This was working fine but I have just gone through it again while writing a test for it and realise it isn't working anymore, I can't figure out why or what has changed to break it.
Categories controller
def update
if #category.update category_params
redirect_to new_guide_category_item_path(#guide, #category)
flash[:info] = "Updated successfully"
else
render 'edit'
end
end
private
def category_params
params.require(:category).permit(:name, :template)
end
edit.html.erb
<%= render 'shared/error_messages', object: f.object %>
.....
<%= form_for([#guide, #category], url: guide_category_path) do |f| %>
<%= f.label :name, "Category name" %>
<%= f.text_field :name %>
<%= f.label :template, "Template" %>
<%= f.text_area :template, { :id => 'edit' } %>
<%= f.submit "Save", :value => "Save Template" %>
<% end %>
model
validates :name, presence: true, length: { maximum: 255 }, uniqueness: { scope: :guide_id, case_sensitive: false },
exclusion: { in: %w( guide guides category categories item items page pages post posts tag tags key keys item key item keys item-key item-keys item_key item_keys mod moderator mods moderators admin admins), message: "%{value} cant be taken." },
format: { with: /\A[a-zA-Z0-9 -]+\z/, message: "only allows letters, numbers, spaces and '-'" }
routes
resources :guides do
resources :categories, only: [:new, :create, :edit, :update] do
end
end
Anyone have an idea of what might be going wrong?
Edit added log output
Started PATCH "/guides/ghj/categories/ijijij" for ::1 at 2016-02-11 14:08:04 +1100
Processing by CategoriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"IqiUJ8wF8ZY4t8f91+t4aOMc9xenx/F2beKjKs9GY7JzLD6ZgPYDY1ueC2s+OIDL+PjROVtMe2+GvgYdan1CDQ==", "category"=>{"name"=>"ijijijddd", "template"=>""}, "commit"=>"Save Template", "guide_id"=>"ghj", "id"=>"ijijij"}
[1m[35mUser Load (0.2ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
[1m[36mGuide Load (0.1ms)[0m [1mSELECT "guides".* FROM "guides" WHERE "guides"."slug" = ? ORDER BY "guides"."id" ASC LIMIT 1[0m [["slug", "ghj"]]
[1m[35mCategory Load (0.1ms)[0m SELECT "categories".* FROM "categories" WHERE "categories"."slug" = ? ORDER BY "categories"."id" ASC LIMIT 1 [["slug", "ijijij"]]
[1m[36m (0.1ms)[0m [1mSELECT "category_item_keys"."name" FROM "category_item_keys" WHERE "category_item_keys"."category_id" = ?[0m [["category_id", 6]]
[1m[35m (0.0ms)[0m SELECT "check_category_item_keys"."name" FROM "check_category_item_keys" WHERE "check_category_item_keys"."category_id" = ? [["category_id", 6]]
[1m[36m (0.1ms)[0m [1mSELECT "category_item_keys"."name" FROM "category_item_keys" WHERE "category_item_keys"."category_id" = ? AND "category_item_keys"."key_type" = ?[0m [["category_id", 6], ["key_type", 1]]
[1m[35m (0.0ms)[0m SELECT "category_item_keys"."name" FROM "category_item_keys" WHERE "category_item_keys"."category_id" = ? AND "category_item_keys"."key_type" = ? [["category_id", 6], ["key_type", 2]]
[1m[36m (0.1ms)[0m [1mSELECT "category_item_keys"."name" FROM "category_item_keys" WHERE "category_item_keys"."category_id" = ? AND "category_item_keys"."key_type" = ?[0m [["category_id", 6], ["key_type", 3]]
[1m[35mGameModsRelationship Exists (0.1ms)[0m SELECT 1 AS one FROM "game_mods_relationships" WHERE "game_mods_relationships"."user_id" = ? AND "game_mods_relationships"."category_id" = 3 LIMIT 1 [["user_id", 1]]
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35mCategoryItemKey Exists (0.1ms)[0m SELECT 1 AS one FROM "category_item_keys" WHERE ("category_item_keys"."name" IS NULL AND "category_item_keys"."guide_id" IS NULL) LIMIT 1
[1m[36mCategory Exists (0.1ms)[0m [1mSELECT 1 AS one FROM "categories" WHERE (LOWER("categories"."name") = LOWER('ijijijddd') AND "categories"."id" != 6 AND "categories"."guide_id" = 3) LIMIT 1[0m
[1m[35m (0.0ms)[0m rollback transaction
[1m[36mCACHE (0.0ms)[0m [1mSELECT 1 AS one FROM "game_mods_relationships" WHERE "game_mods_relationships"."user_id" = ? AND "game_mods_relationships"."category_id" = 3 LIMIT 1[0m [["user_id", 1]]
Rendered shared/_error_messages.html.erb (0.5ms)
Rendered categories/edit.html.erb within layouts/application (5.6ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (0.7ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 157ms (Views: 145.1ms | ActiveRecord: 1.1ms)`
You need to add error_messages helper tag in the partial. That handles all error messages and show it properly.
It looks like your database has an existing record with the same name. Try inputting a unique name in. In your model, it is checking for :uniqueness.

Resources