I am in the activeadmin dashboard. I am trying to only show customers of the current_user but I get an error undefined local variable or methodcurrent_user'`
here is my code for the dashboard:
section "Recent Customers" do
table_for Customer.owned_by(current_user).limit(5) do
column "Name" do |customer|
link_to customer.name, admin_customers_path(customer)
end
column :phone
column :email, :sortable => :email do |customer|
link_to customer.email, "mailto:#{customer.email}"
end
end
strong { link_to "View All Customers", admin_customers_path }
end
in active_admin try current_admin_user
Related
I am new to Sinatra and trying to create a post request which would add some data into "City" table in PGadmin. But, I am getting an error when trying to add it. The get request works fine, and posting static data on the post endpoint also works fine, but posting data doesn't I am not sure what's wrong since the migration and the model for city does exist. Here's the code:
city.rb
class City < UserDB
validates_presence_of :name, :pin
def as_json(options = {})
super({only: [:city, :pin]})
end
end
migration:
class CreateCity < ActiveRecord::Migration[6.0]
def change
create_table :city do |t|
t.string :name
t.integer :pin
end
end
end
module Users
module V1
class CityController< LocalAPI::ApplicationBase
before do
content_type 'application/json'
end
get '/' do
city=City.all
if city
"city exists"
else
"doesn't exist"
end
end
post '/add' do
params = JSON.parse request.body.read
#name= params['name']
#pin= params['pin']
#city=City.new(name:#name,pin:#pin)
if #city.save
return output(200, #city.as_json)
else
"cant create"
end
end
end
end
end
I am trying to post the below content through postman:
{
"name": "hamilton",
"pin":"222"
}
Please note that the route is configured and it does work when I visit the url. Also have ran db:migrate
I could not update because of params problem I guess. Even though flash said "updated successfully" but nothing changed. I used User model and Skill model which make things more complicated.
Please tell me how to fix this situation.
Skills controller:
class SkillsController < UsersController
def update
#skill=Skill.find_by(id:params[:id])
if #skill.update_attributes(skills_params)
flash[:success]="Updated Successfully"
redirect_to users_url
else
flash[:danger]="no infomation"
render #skill
end
end
private
def skills_params
params.permit(:id,:skill_type, :tech, :web_name, :web_url, :web_image, :experience)
end
end
skills/edit.html.erb:
<%= form_for #skill do |f| %>
<%= f.label:skill_type %>
<%= text_field :skill_type, value=#skill.skill_type, :placeholder =>
#skill.skill_type %>
<%= f.label:tech %>
<%= text_field :tech, value=#skill.tech,:placeholder => #skill.tech %>
<!-- More fields -->
<%= f.submit %>
<% end %>
Server logs:
Processing by SkillsController#update as HTML
Parameters{"utf8"=>"✓","authenticity_token"=>"XrbQqewGHBC8yoFHFg9tkg9sCTtscV+QjUMgaw2pdXEsUk+NiCJHSHVkj/N/bhjD1uaExeop4uSXb6hCCKGD/Q==", "skill_type"=>{"0"=>"1"}, "tech"=>{"shitunnkokoko"=>"aaaa"}, "web_name"=>{"ssasdesilgffgfo"=>"aaaaaa"}, "web_url"=>{"googleeee.com"=>"aaa#aaaa"}, "web_image"=>{"dfsafsafasfasdf"=>"bbbbb"}, "experience"=>{"javaaaaaa"=>"sssss"}, "commit"=>"変更する", "id"=>"5"}
Skill Load (0.1ms) SELECT "skills".* FROM "skills" WHERE "skills"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
Unpermitted parameters: :utf8, :_method, :authenticity_token, :skill_type, :tech, :web_name, :web_url, :web_image, :experience, :commit
(0.1ms) begin transaction
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
(0.0ms) commit transaction
**
Additional Information
**
skill.ruby
class Skill < ApplicationRecord
belongs_to :user
# mount_uploader :picture, PictureUploader
validates :user_id,presence:true
validates :experience, length:{maximum:500}
end
user.rb
class User < ApplicationRecord
before_save {self.email = email.downcase}
validates :name, presence:true,length:{maximum:50}
VALID_EMAIL_FORM=/\A[a-zA-Z0-9_\#!$%&`'*+\-{|}~^\/=?\.]+#[a-zA-Z0-9]
[a-zA-Z0-9\.-]+\z/
validates :email, presence:true,length:{maximum:255},
format: { with: VALID_EMAIL_FORM},
uniqueness:{ case_sensitive: false }
has_secure_password
validates :password, length:{minimum:6},presence:true
def skills
return Skill.find_by(user_id:self.id)
end
end
skill table schema
sqlite> .schema skills
CREATE TABLE "skills" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT
NULL, "skill_type" integer DEFAULT NULL, "tech" varchar DEFAULT NULL,
"web_name" varchar DEFAULT NULL, "web_url" text DEFAULT NULL,
"web_image" varchar DEFAULT NULL, "experience" text DEFAULT NULL,
"created_at" datetime NOT NULL, "updated_at" datetime NOT NULL,
"picture" varchar DEFAULT NULL, "user_id" integer);
CREATE INDEX "index_skills_on_user_id_and_created_at" ON "skills"
("created_at");
CREATE INDEX "index_skills_on_user_id" ON "skills" ("user_id");
users table schema
sqlite> .schema users
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"name" varchar DEFAULT NULL, "email" varchar DEFAULT NULL,
"created_at" datetime NOT NULL, "updated_at" datetime NOT NULL,
"password_digest" varchar DEFAULT NULL);
CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email");
My guess is the #skill is empty.
In the edit Action in the SkillsController you load #skill and #user by the same id (id:params[:id])
#user=User.find_by(id:params[:id])
#skill=Skill.find_by(id:params[:id])
I am trying to create a review form in my rails app but when i click on the submit button, the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:
Google API error: over query limit.
(0.1ms) rollback transaction
Update
I am not only getting the Google API error. sometimes i get this error and other time i only get rollback transaction only.
This is the Reviews Controller:
class ReviewsController < ApplicationController
# check if logged in
before_action :check_login, except: [:index, :show]
def index
# this is our list page for our reviews
#price = params[:price]
#cuisine = params[:cuisine]
#location = params[:location]
# start with all the reviews
#reviews = Review.all
# filtering by price
if #price.present?
#reviews = #reviews.where(price: #price)
end
# filter by cuisine
if #cuisine.present?
#reviews = #reviews.where(cuisine: #cuisine)
end
# search near the location
if #location.present?
#reviews = #reviews.near(#location)
end
end
def new
# the form for adding a new review
#review = Review.new
end
def create
# take info from the form and add it to the model
#review = Review.new(form_params)
# and then associate it with a user
#review.user = #current_user
# we want to check if the model can be saved
# if it is, we're go the home page again
# if it isn't, show the new form
if #review.save
flash[:succces] = "Your review was posted!"
redirect_to root_path
else
# show the view for new.html.erb
render "new"
end
end
def show
# individual review page
#review = Review.find(params[:id])
end
def destroy
# find the individual review
#review = Review.find(params[:id])
# destroy if they have access
if #review.user == #current_user
#review.destroy
end
# redirect to the home page
redirect_to root_path
end
def edit
# find the individual review (to edit)
#review = Review.find(params[:id])
if #review.user != #current_user
redirect_to root_path
elsif #review.created_at < 4.hours.ago
redirect_to review_path(#review)
end
end
def update
# find the individual review
#review = Review.find(params[:id])
if #review.user != #current_user
redirect_to root_path
else
# update with the new info from the form
if #review.update(form_params)
# redirect somewhere new
redirect_to review_path(#review)
else
render "edit"
end
end
end
def form_params
params.require(:review).permit(:title, :restaurant, :body, :score,
:ambiance, :cuisine, :price, :address)
end
end
This is the Review form page:
<%= simple_form_for #review do |f| %>
<%= f.input :title %>
<%= f.input :restaurant %>
<%= f.input :address %>
<%= f.input :body %>
<%= f.input :cuisine %>
<%= f.input :price %>
<%= f.input :score %>
<%= f.input :ambiance %>
<%= f.button :submit %>
<% end %>
The Review Model
class Review < ApplicationRecord
# add an association that has a 1-to-many relationship
has_many :comments
has_many :bookmarks
# add an association to the user
belongs_to :user
geocoded_by :address
after_validation :geocode
validates :title, presence: true
validates :body, length: { minimum: 10 }
validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
validates :restaurant, presence: true
validates :address, presence: true
def to_param
id.to_s + "-" + title.parameterize
end
end
This is My Schema file
create_table "reviews", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "score"
t.string "restaurant"
t.integer "price"
t.string "cuisine"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "phone_number"
t.string "ambiance"
t.text "address"
t.float "latitude"
t.float "longitude"
t.integer "user_id"
end
You have two problems:
you are going over Google's Geocoding API quota as evidenced by the error message "over query limit"
Most likely because of that, your model cannot be saved is rolled back. The geocoding API call fails, it doesn't save.
I would check the Google API Console and see if you have actually hit their quota (possible if you're running multiple tests and you're on their free tier of service). If you have not hit the limit, file a support request with Google API.
You probably reached your Google API quota.
In model you have geocoded_by ... that is used by gem geocoder so have a look at that.
Google has per second limit as well as per day limit link
I m trying to build a shopping cart for a website. I have the cart working so you can add to the cart. The problem I am having is when I try and checkout items in the cart and try to submit my order. I am getting the following error:
ActiveModel::MissingAttributeError in OrdersController#create
along with
can't write unknown attribute `order_id'
The problem is highlighting this piece of code in my orders_controller.rb file
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id]) session[:cart_id] = nil
I just cant seem to fix this error.
Below is the create method in my orders_controller.rb file
def create
#order = Order.new(order_params)
#order.add_line_items_from_cart(#cart)
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
format.html { redirect_to store_url,
notice: 'Thank you for your order.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
my migration file
class AddOrderToLineItem < ActiveRecord::Migration
def change
add_column :line_items, :order, :reference
end
end
my order.rb model
class Order < ActiveRecord::Base
has_many :line_items, dependent: :destroy
validates :name, :address, :email, presence: true
PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order" ]
validates :pay_type, inclusion: PAYMENT_TYPES
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
migration order table
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :name
t.text :address
t.string :email
t.string :pay_type
t.timestamps
end
end
end
Ok, I think I see the problem. Your migration for orders in line items probably didn't create the order_id column you expected, it probably created an orders column or something.
Verify that this is the case in the database. If so, undo your previous migration and try this instead:
class AddOrderToLineItem < ActiveRecord::Migration
def change
add_column :line_items, :order_id, :int
end
end
If not, please respond to this answer.
i try to find out how i can show associations deeper than one level.
Show at my FORM, i just done it there:
form do |f|
f.inputs "Details" do
f.input :name
f.input :item_category
f.input :resource
f.input :status
end
f.inputs "Actions" do
f.semantic_errors *f.object.errors.keys
f.has_many :item_actions, :allow_destroy => true, :heading => 'Planets', :new_record => true do |obj|
obj.input :action
obj.input :status
obj.input :_destroy, :as=>:boolean, :required => false, :label=>'Remove'
obj.has_many :item_action_skills, :heading => "Skills" do |ias|
ias.input :skill
ias.input :level
end
end
end
f.actions
end
You can see, i show has_many :item_actions and going one level deeper to item_action.item_action_skills. On this form is works perfect.
Now i'll want it on the show page too. My code:
show do |obj|
attributes_table do
row :name
row :item_category
row(:resource) {|obj| status_tag((obj.resource ? 'yes' : 'no'), (obj.resource ? :ok : :error))}
row(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
end
panel "Actions" do
table_for obj.item_actions do
column :action
column(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
end
end
active_admin_comments
end
I write table_for, but how to go now to the next association?
I want the item_action.item_action_skills.
I have no idea. Any idea?
Thanks!
Ruby 1.9.3
Rails 3.2.14
ActiveAdmin 0.6.0
Try this:
panel "Actions" do
table_for obj.item_actions do
column :action
column(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
column("skills"){|resource|
table_for resource.item_action_skills do
column(:your_column)
end
}
end
end