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
Related
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()
}
});
});
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.
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
I have a checkout sequence in my app like this:
Cart - The user's tax is calculated and they hit a checkout button
charges#address - There is a form to update the shipping address in the user table
charges#shipping - The user chooses a shipping method (which updates order.total in the database)
charges#new - Stripe actually makes a charge
My issue is that, for some reason, the charges#shipping (step 3 is skipped, it goes from 2 to 4) is being skipped over entirely. The information for each step is below.
Step 2 Information
The form:
<%= simple_form_for(#user, url: user_path(#user), html: { method: :put }) do |f| %>
<div class="form-inputs text-left">
<div class="form-group col-sm-6">
<%= f.label :street_address_1 %>
<%= f.text_field :street_address_1, class: "form-control" %>
</div>
<div class="form-group col-sm-6">
<%= f.label :street_address_2 %>
<%= f.text_field :street_address_2, class: "form-control" %>
</div>
<div class="form-group col-sm-6">
<%= f.label :city %>
<%= f.text_field :city, class: "form-control" %>
</div><div class="form-group col-sm-3 col-xs-6">
<%= f.label :state %>
<%= f.text_field :state, class: "form-control" %>
</div><div class="form-group col-sm-3 col-xs-6">
<%= f.label :zip %>
<%= f.text_field :zip, class: "form-control" %>
</div><div class="form-group col-sm-6">
<%= f.label :provence %>
<%= f.text_field :provence, class: "form-control" %>
</div><div class="form-group col-sm-6">
<%= f.label :country %>
<%= f.text_field :country, class: "form-control" %>
</div><div class="form-group">
<%= f.hidden_field :has_shipping, value: true %>
</div>
</div> <!-- form inputs -->
<%= f.button :submit, "Calculate Shipping" %>
<% end %>
The method in users_controller which should be sending it to the charges#shipping page, but it ends up on charges#new:
def update
#user = User.find(params[:id])
#user.update_attributes(account_update_params)
if #user.update(account_update_params)
redirect_to charges_shipping_path
else
render :back
flash[:notice] = "Something is amuck."
end
end
def account_update_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :phone, :admin, :stripe_customer_id, :street_address_1, :street_address_2, :city, :state, :zip, :provence, :country, :has_shipping)
end
Here's what's happening in the server:
Started PUT "/users/1" for ::1 at 2017-05-16 10:04:10 -0700
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"R2ZDErL9UQ6nPNyYDI9FDeOp0x29t+/STWIkTKeShz2WWdO8kWu+z6V5NS/EKI6uiLcCAQBbwbsRMlhGs8v2VA==", "user"=>{"street_address_1"=>"10 Oak View Drive", "street_address_2"=>"Test", "city"=>"Aliso Viejo", "state"=>"CA", "zip"=>"92656", "provence"=>"", "country"=>"US", "has_shipping"=>"true"}, "commit"=>"Calculate Shipping", "id"=>"1"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
(0.1ms) commit transaction
(0.0ms) begin transaction
(0.0ms) commit transaction
Redirected to http://localhost:3000/charges/shipping
Completed 302 Found in 5ms (ActiveRecord: 0.3ms)
Started GET "/charges/shipping" for ::1 at 2017-05-16 10:04:10 -0700
Processing by ChargesController#shipping as HTML
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
CACHE (0.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
(0.1ms) begin transaction
OrderItem Load (0.1ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 5]]
Product Load (0.0ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", "t"], ["id", 2]]
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", "t"], ["id", 1]]
(0.0ms) commit transaction
156.95
(0.0ms) begin transaction
(0.0ms) commit transaction
Redirected to http://localhost:3000/charges/new
CACHE (0.0ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 5]]
CACHE (0.0ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", true], ["id", 2]]
CACHE (0.0ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", true], ["id", 1]]
Completed 302 Found in 1965ms (ActiveRecord: 0.6ms)
Started GET "/charges/new" for ::1 at 2017-05-16 10:04:12 -0700
Processing by ChargesController#new as HTML
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
Rendered charges/_shipping.html.erb (2.1ms)
Rendered charges/new.html.erb within layouts/application (3.1ms)
CACHE (0.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
(0.1ms) SELECT COUNT(*) FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 5]]
CACHE (0.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 5]]
OrderItem Load (0.1ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 5]]
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", "t"], ["id", 2]]
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT 1 [["active", "t"], ["id", 1]]
Rendered layouts/_cart_text.html.erb (6.1ms)
Completed 200 OK in 82ms (Views: 80.6ms | ActiveRecord: 0.6ms)
Here's the form in step 3 (the one being skipped, though all that really matters here is that it's a form_for(#order):
<h3>Shipping Rates</h3>
<% shipping_choices = [] %>
<% #ups_rates.each do |rate| %>
<% choice = [] %>
<% choice << number_to_currency(rate[1]/100) %>
<% choice << number_to_currency(rate[1]/100).to_s + " - " + rate[0].to_s %>
<% shipping_choices << choice %>
<% end %>
<%= simple_form_for order_path(#order) do |f| %>
<div class="row">
<div class="form-inputs text-left">
<div class="form-group col-sm-6">
<%= f.collection_radio_buttons :shipping, shipping_choices, :first, :last, item_wrapper_class: :block_radio_button_collection %>
</div>
</div> <!-- form inputs -->
</div> <!-- choices row -->
<div class="row">
<%= f.button :submit, "Calculate Shipping" %>
</div>
<% end %>
And here's the order#update method:
def update
#order = current_order
if #order.update(order_params)
redirect_to charges_address_path
else
render :back
flash[:notice] = "Something is amuck."
end
end
This is a very strange problem for me. Can anyone see where I'm going wrong?
Additional Information
As requested, here is my (unfortunately long) `charges#shipping` method:
def shipping
#user = current_user
#products = current_order.order_items.all
#order = current_order
if #order.update(order_params)
new_total = #order.total + #order.shipping
#order.update_attributes(total: new_total)
redirect_to new_charge_path
else
render :back
flash[:notice] = "Something is amuck."
end
#envelope_weight = 0
#not_envelope = 0
#products.each do |thing|
if thing.product.envelope
#envelope_weight += thing.product.weight
else
#not_envelope += 1
end
end
if #not_envelope == 0
# shipping for envelope
else
packages = []
#products.each do |thing|
unless thing.product.envelope
if thing.id == 1
packages << ActiveShipping::Package.new( (thing.product.weight + #envelope_weight ) * 16,
[thing.product.box_length, thing.product.box_width, thing.product.box_depth],
units: :imperial)
else
packages << ActiveShipping::Package.new( thing.product.weight * 16,
[thing.product.box_length, thing.product.box_width, thing.product.box_depth],
units: :imperial)
end # envelope weight if else
end #unless
end ## each do
end # not envelope if/else
origin = ActiveShipping::Location.new( country: 'US', state: 'CO', city: 'Sedalia', zip: '80135')
if #user.country == 'US'
destination = ActiveShipping::Location.new( country: #user.country, state: #user.state, city: #user.city, zip: #user.zip)
else
destination = ActiveShipping::Location.new( country: #user.country, province: #user.state, city: #user.city, postal_code: #user.zip)
end # if/else for country
ups = ActiveShipping::UPS.new(login: 'lizbayardelle', password: 'UPSpassw0rd', key: '3D287D7B39D0D398')
ups_response = ups.find_rates(origin, destination, packages)
#ups_rates = ups_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}
usps = ActiveShipping::USPS.new(login: '380LINCH6422')
usps_response = usps.find_rates(origin, destination, packages)
#usps_rates = usps_response.rates.sort_by(&:price).collect {|rate| [rate.service_name, rate.price]}
end
First you redirected from UsersController#update to ChargesController#shipping, it went into the shipping action where the condition for if #order.update(order_params) became true as order_params is nil here and hence it redirected to ChargesController#new
When you do a redirect_to in rails, it redirects as a GET request. When you submit a form, it will be POST/PUT by default(unless you change it).
You can even see in your logs, how all redirects are going in as GET.
It is not advisable to use same action for both. If you do want to use same action make sure you are adding a check for request.method=='GET' or request.method=='POST' in them.
From what I see in your shipping action code, it was written to handle form submits(POST) and not for handling GET requests via redirects.
So either handle it logically or seperate it into seperate actions, one to render the form and other to handle the form submit.
P.S. Also do not forget to add 'and return' after each redirect.
redirect_to charges_shipping_path and return
In my rails 5 app, I have a form (below) that is loading correctly, yet not updating. No notification of errors (should pass all validations (only on presence = true)).
Error
param is missing or the value is empty: tag
pointing to the tag_params method.
All help, suggestions, improvement, simplification welcome!
Controller
def update
tagable = detect_tagable
#tag = tagable.tags.find(params[:id])
#tag.update(tag_params)
render '_tag_update'
end
def tag_params
params.require(:tag).permit(:content, :location, :tagtype_id, annotation_attributes: { annotation_ids:[] }, document_attributes: { document_ids:[] })
end
Routes
Rails.application.routes.draw do
root 'dashboard#index'
devise_for :users
resources :users, :documenttypes, :tagtypes, :business_partners
resources :documents do
resources :comments, :tags
get "pdf", on: :member
end
resources :annotations do
resources :comments, :tags
get "pdf", on: :member
end
get "annotations/:id/annotate" => "annotations#annotate", as: 'annotate'
Form:
<%= simple_form_for [#tag.tagable, #tag], html: { class: 'form-horizontal', multipart: true },
wrapper: :horizontal_form,
wrapper_mappings: {
check_boxes: :horizontal_radio_and_checkboxes,
radio_buttons: :horizontal_radio_and_checkboxes,
boolean: :horizontal_boolean
} do |f| %>
<%= f.error_notification %>
<%= f.input :content, placeholder: 'Tagged content'%>
<%= f.association :tagtype, prompt: 'Select tag type', :collection => Tagtype.active.order(:name).where(:documenttype => #tag.tagable.documenttype_id) %>
<%= f.input :location, prompt: 'add as x1, y1, x2, y2' %>
<%= f.button :submit %>
<% end -%>
Rails server returns this (appears to be executed)
Started PATCH "/annotations/6/tags/46" for ::1 at 2016-10-15 16:15:09 +0200
Processing by TagsController#update as HTML
Parameters: {"authenticity_token"=>"7JMnYxy00zQXLIEfETSGWcMxPQFwNMYRJRyCeL9RMAQYtLygrf3UjamlZQdR/ajgTY2wH6DKOTeLE6yAUqbc6w==", "annotation_id"=>"6", "id"=>"46"}
User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 6], ["LIMIT", 1]]
Annotation Load (1.1ms) SELECT "annotations".* FROM "annotations" WHERE "annotations"."id" = $1 LIMIT $2 [["id", 6], ["LIMIT", 1]]
Tag Load (1.0ms) SELECT "tags".* FROM "tags" WHERE "tags"."tagable_id" = $1 AND "tags"."tagable_type" = $2 AND "tags"."id" = $3 LIMIT $4 [["tagable_id", 6], ["tagable_type", "Annotation"], ["id", 46], ["LIMIT", 1]]
(0.2ms) BEGIN
Tagtype Load (0.5ms) SELECT "tagtypes".* FROM "tagtypes" WHERE "tagtypes"."id" = $1 LIMIT $2 [["id", 5], ["LIMIT", 1]]
(0.2ms) COMMIT
Rendering tags/_tag_update.html.erb within layouts/application
Annotation Load (0.4ms) SELECT "annotations".* FROM "annotations" WHERE "annotations"."id" = $1 LIMIT $2 [["id", 6], ["LIMIT", 1]]
Tagtype Load (1.0ms) SELECT "tagtypes".* FROM "tagtypes" WHERE "tagtypes"."active" = $1 AND "tagtypes"."documenttype_id" = 2 ORDER BY "tagtypes"."name" ASC [["active", true]]
Rendered tags/_tag_update.html.erb within layouts/application (43.0ms)
Rendered shared/_menu.html.erb (2.9ms)
Completed 200 OK in 220ms (Views: 203.3ms | ActiveRecord: 6.1ms)