Update does not work... params problem I guess - ruby

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])

Related

rollback transaction error rails from google geocoding api

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

nested validation for uniqueness doesn't work in rails 4 project

I have two models - Category and Property with has_balongs_to_many association. I use nested_form gem. So, Category has many properties. When I create new category I can create properties.
Category model category.rb:
class Category < ActiveRecord::Base
# relationships
has_many :categories_properties
has_many :properties, through: :categories_properties, inverse_of: :categories
# allows to create and destroy nested objects
accepts_nested_attributes_for :properties, allow_destroy: true
# validation
validates :title, presence: true, length: { minimum: 3, maximum: 128 }, uniqueness: true
end
Property model property.rb:
class Property < ActiveRecord::Base
# relationships
has_many :categories_properties
has_many :categories, through: :categories_properties
# validation
validates :title, presence: true, length: { minimum: 3, maximum: 128 }, uniqueness: true
end
As you see a have uniqueness: true validation in property model.
When I'm trying to create the same properties using rails console or on the category edit page - it gives me error like "property with this name already exists." It's correct and it should be.
But on the category new page, when I create the same properties (as you see in screenshot) it doesn't give me errors, validation doesn't work and it creates me new category with two same properties.... What's wrong? Please help.
Here's log:
Started POST "/categories" for 127.0.0.1 at 2014-09-01 14:28:19 +0300
Processing by CategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"AFf8upQco8ZqJBS8QdpU9RIRpvAW1VLnBSm1bw6rxss=", "category"=>{"title"=>"Category", "description"=>"category description", "order"=>"12345", "icon"=>"http://4.bp.blogspot.com/-LOX6N2kXXaY/T5UtocrGRnI/AAAAAAAAAFU/EW_OZTHT1PI/s1600/1210167310_174374.jpg", "parent_id"=>"", "properties_attributes"=>{"1409570848547"=>{"title"=>"same properties", "_destroy"=>"false"}, "1409570857024"=>{"title"=>"same properties", "_destroy"=>"false"}}}, "commit"=>"Create Category"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.4ms) SELECT "categories"."id", "categories"."title" FROM "categories"
CACHE (0.0ms) SELECT "categories"."id", "categories"."title" FROM "categories"
(0.2ms) BEGIN
Property Exists (0.4ms) SELECT 1 AS one FROM "properties" WHERE "properties"."title" = 'same properties' LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "properties" WHERE "properties"."title" = 'same properties' LIMIT 1
Category Exists (0.6ms) SELECT 1 AS one FROM "categories" WHERE "categories"."title" = 'Category' LIMIT 1
SQL (0.5ms) INSERT INTO "categories" ("created_at", "description", "icon", "order", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["created_at", "2014-09-01 11:28:19.908849"], ["description", "category description"], ["icon", "http://4.bp.blogspot.com/-LOX6N2kXXaY/T5UtocrGRnI/AAAAAAAAAFU/EW_OZTHT1PI/s1600/1210167310_174374.jpg"], ["order", 12345], ["title", "Category"], ["updated_at", "2014-09-01 11:28:19.908849"]]
SQL (0.3ms) INSERT INTO "properties" ("created_at", "title", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2014-09-01 11:28:19.910971"], ["title", "same properties"], ["updated_at", "2014-09-01 11:28:19.910971"]]
SQL (0.4ms) INSERT INTO "categories_properties" ("category_id", "created_at", "property_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["category_id", 77], ["created_at", "2014-09-01 11:28:19.921763"], ["property_id", 90], ["updated_at", "2014-09-01 11:28:19.921763"]]
SQL (0.4ms) INSERT INTO "properties" ("created_at", "title", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2014-09-01 11:28:19.947583"], ["title", "same properties"], ["updated_at", "2014-09-01 11:28:19.947583"]]
SQL (0.4ms) INSERT INTO "categories_properties" ("category_id", "created_at", "property_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["category_id", 77], ["created_at", "2014-09-01 11:28:19.950243"], ["property_id", 91], ["updated_at", "2014-09-01 11:28:19.950243"]]
(0.5ms) COMMIT
Redirected to http://0.0.0.0:3000/categories/77
Completed 302 Found in 129ms (ActiveRecord: 21.8ms)
Add validation method to category model:
def properties_uniq? params
properties = params.map{ |_,property| property[:title] }
if properties.uniq.length < properties.length
errors.add(:category, "Properties duplication are not allowed." )
return false
end
true
end
Check attributes in controller (when save category):
def create
#category = Category.new(category_params)
respond_to do |format|
if #category.save && #category.properties_uniq?(params[:category][:properties_attributes])
format.html { redirect_to #category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: #category }
else
format.html { render :new }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end

How to stop DataMapper from double query when limiting columns/fields?

I'm not sure if I'm at fault here or if my approach is wrong with this.
I want to fetch a user (limiting columns/fields only to name, email, id):
#user = User.first(:api_key => request.env["HTTP_API_KEY"], :fields => [:id, :name, :email])
The output in the command line is correct as follows:
SELECT "id", "name", "email" FROM "users" WHERE "api_key" = '90e20c4838ba3e1772ace705c2f51d4146656cc5' ORDER BY "id" LIMIT 1
Directly after the above query, I have this code:
render_json({
:success => true,
:code => 200,
:user => #user
})
render_json() looks like this, nothing special:
def render_json(p)
status p[:code] if p.has_key?(:code)
p.to_json
end
The problem at this point is that the #user variable contains the full user object (all other fields included) and DataMapper has made an additional query to the database to fetch the fields not included in the :fields constraint, from the logs:
SELECT "id", "password", "api_key", "premium", "timezone", "verified", "notify_me", "company", "updated_at" FROM "users" WHERE "id" = 1 ORDER BY "id"
My question is this: how do I stop DM from performing the additional query? I know it has to do with it's lazy loading architecture and that returning the #user variable in JSON assumes that I want the whole user object. I particularly don't want the password field to be visible in any output representation of the user object.
The same behaviour can be seen when using DM's own serialisation module.
I think you should use an intermediate object for json rendering.
First, query the user from database :
db_user = User.first(:api_key => request.env["HTTP_API_KEY"], :fields => [:id, :name, :email])
Then, create a "json object" to manipulate this user :
#user = { id: db_user.id, name: db_user.name, email: db_user.email }

Show page, show associations

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

I am having problems with getting current_user data

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

Resources