I'm new to ROR. The query I created below is functioning properly. I'm trying to prepare an interrogation. But I didn't succeed. The query is as follows;
#rad_user_group.groupname = SELECT groupname FROM radgrs INNER JOIN nas WHERE radgrs.grdefault = true AND radgrs.tenant_id = nas.tenant_id AND nas.realipaddr = "192.168.22.175" AND nas.active = true
How do I make a switch case for the following queries in another question? Returns NULL if the query fails.
Thank you for caring.
def realipaddr
request.remote_addr
end
def create
#rad_check = RadCheck.new(rad_check_params)
#rad_check.tenant_id = Na.find_by(realipaddr: realipaddr, active: :true).tenant_id
respond_to do |format|
if #rad_check.save
format.html { redirect_to #rad_check, notice: 'Rad check was successfully created.' }
format.json { render :show, status: :created, location: #rad_check }
else
format.html { render :new }
format.json { render json: #rad_check.errors, status: :unprocessable_entity }
end
end
end
RadCheck Model
class RadCheck < ApplicationRecord
has_one :rad_user_group, dependent: :destroy
after_initialize :add_rad_user_group
before_save :set_radcheck
def add_rad_user_group
self.rad_user_group ||= RadUserGroup.new if self.new_record?
end
def set_radcheck
self.rad_user_group.username = username
self.op = ":="
self.attribu = "Cleartext-Password"
end
end
class CreateRadChecks < ActiveRecord::Migration[5.2]
def change
create_table :rad_checks do |t|
t.integer :tenant_id
t.string :username
t.string :password
t.string :attribu
t.string :op
t.string :realipaddr
t.string :groupname
t.timestamps
end
end
end
Radgr Model
class Radgr < ApplicationRecord
end
class CreateRadgrs < ActiveRecord::Migration[5.2]
def change
create_table :radgrs do |t|
t.integer :tenant_id
t.string :groupname
t.string :realipaddr
t.boolean :grdefault
end
end
end
RadUserGroup Model
class RadUserGroup < ApplicationRecord
belongs_to :rad_check
end
class CreateRadUserGroups < ActiveRecord::Migration[5.2]
def change
create_table :rad_user_groups do |t|
t.integer :tenant_id
t.string :username
t.string :groupname
t.references :rad_check, foreign_key: true
t.timestamps
end
end
end
Na Model
class Na < ApplicationRecord
end
class CreateNas < ActiveRecord::Migration[5.2]
def change
create_table :nas do |t|
t.integer :tenant_id
t.string :nasname
t.string :realipaddr
t.boolean :active
end
end
end
PhpMyAdmin Query
You should better organize the object associations. The objects obviously having some sort of relations.
Like Radgr model and Na model. I think you can make relation between these two, so later you can use query command all = Radgr.includes(:nas).where("nas.realipaddr =?", "192.168.22.175") or something similar.
Also here is a good site for converting SQL to ActiveRecord query, but you need here to create your models and associations for testing.
Please check:
http://www.scuttle.io/
Related
NOTE:
Yes, I know that there is supposedly duplicate posts on this matter, but the latest one that I saw is from 10 years ago (Link to that post), was never solved, and none of the posts had gotten an answer that could solve my issue, thus here I am...
I have been trying to make an mock website where an User can make Binders, that hold Decks, which hold Flashcards.
My problem here is (most likely) with my joins table, the Flashcard. Flashcard is my joins table because I am trying to also create an page where an User can browse through all of the Flashcards made by every User, and add it to one of their Decks (basically, shared access).
Every time I try to create an Flashcard, I get this error:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly Exception: Cannot modify association 'User#flashcards' because it goes through more than one other association.
Here is my code:
User model:
class User < ApplicationRecord
has_secure_password
has_many :binders
has_many :decks, through: :binders
has_many :flashcards, through: :decks
end
Binder model:
class Binder < ApplicationRecord
belongs_to :user
has_many :decks
has_many :flashcards, through: :decks
end
Deck model:
class Deck < ApplicationRecord
belongs_to :binder
has_many :flashcards
end
Flashcard model:
class Flashcard < ApplicationRecord
belongs_to :user
belongs_to :deck
validates :user, :deck, presence: true
end
flashcards_controller.rb:
class FlashcardsController < ApplicationController
def create
flashcard = set_user.flashcards.new(flashcard_params)
flashcard.user_id = user.id
if flashcard.save
render json: flashcard, status: :created
else
render json: {errors: flashcard.errors.full_messages}, status: :unauthorized
end
end
private
def flashcard_params
params.require(:flashcard).permit(:id, :user_id, :deck_id, :question, :answer) # Verify if the user_id is needed from frontend
end
end
My schema.rb:
create_table "binders", force: :cascade do |t|
t.string "name"
t.integer "user_id"
end
create_table "decks", force: :cascade do |t|
t.integer "binder_id"
t.string "name"
end
create_table "flashcards", force: :cascade do |t|
t.integer "user_id"
t.integer "deck_id"
t.string "question"
t.string "answer"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
end
Okay, so I figured out how to fix this issue...
My updated flashcards_controller.rb create method:
def create
deck = current_user.decks.find_by(id: params[:deck_id])
flashcard = deck.flashcards.new(flashcard_params)
flashcard.user_id = current_user.id
if flashcard.save
render json: flashcard, status: :created
else
render json: {errors: flashcard.errors.full_messages}, status: :unauthorized
end
end
This new create method works, because after the Flashcard object is created (but before attempting to save it), the method will keep checking for the new Flashcard object until it is found, assigns the user_id to it, and then attempts to save the new object...
I've been trying to do rake db:seed which normally works for me but now is failing.
Here is the error and the code.
My error logs:
User.rb:
class User < ApplicationRecord
cattr_accessor :current_user
belongs_to :highschool, optional: true
end
High school migration:
class CreateHighschools < ActiveRecord::Migration[5.0]
def change
create_table :highschools do |t|
t.string :secondaryschool
t.timestamps
end
end
end
High School migration reference to User:
class AddHighschoolRefToUsers < ActiveRecord::Migration[5.0]
def change
add_reference :users, :highschools, foreign_key: true
end
end
Highschool.rb:
class Highschool < ApplicationRecord
has_many :users
end
Highschools_controller.rb:
class HighschoolsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def create
#highschool = Highschool.new(highschool_params)
if #highschool.save
render json: #highschool
else
render json: {errors: #highschool.errors.full_messages}
end
end
private
def highschool_params
params.require(:highschool).permit(:secondaryschool)
end
end
Schema.rb:
create_table "highschools", force: :cascade do |t|
t.string "secondaryschool"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Seeds.rb:
Highschool.destroy_all
special = Highschool.create!(Secondaryschool: "Stuyvesant High School")
special2 = Highschool.create!(Secondaryschool: "Brooklyn Tech")
special3 = Highschool.create!(Secondaryschool: "Bronx Science")
Theres a typo:
special = Highschool.create!(secondaryschool: "Stuyvesant High School")
special2 = Highschool.create!(secondaryschool: "Brooklyn Tech")
special3 = Highschool.create!(secondaryschool: "Bronx Science")
I have setup has_many and has_many :through association between a Order,User,Product and Order_detail model as a join table.
Models:
class Order < ActiveRecord::Base
has_many :order_details
belongs_to :user
has_many :products, through: :order_details
end
class OrderDetail < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :order_details
has_many :orders, through: :order_details
end
class User < ActiveRecord::Base
has_many :orders
end
How to save automatically for join table order_details.
Now data save only to order table.
Need to save all products to order_tables for current order and user
class OrdersController < ApplicationController
before_action :authenticate_user!
def index
#order = Order.all
end
def new
# #order = Order.new
#order = current_user.orders.new
end
def create
#order = current_user.orders.new(order_params)
#order.date = Date.today.to_s
if #order.save
# i think this is bad wrong to implementation of functional)
# params[:product_id].each do |detail_product_id|
# #order.order_details.product_id = detail_product_id
# #order.order_details.user_id = current_user
# #order.order_details.save
flash[:success] = "Order was successfully submitted"
redirect_to new_order_path
else
render :new
end
end
private
def order_params
params.require(:order).permit(:date, :product_id => [])
end
end
My schema:
create_table "order_details", force: true do |t|
t.integer "order_id"
t.integer "product_id"
t.integer "quantity"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "orders", force: true do |t|
t.integer "user_id"
t.date "date"
end
add_index "orders", ["user_id"], name: "index_orders_on_user_id", using: :btree
create_table "orders_products", id: false, force: true do |t|
t.integer "order_id"
t.integer "product_id"
end
create_table "products", force: true do |t|
t.string "product_name"
t.integer "product_price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "available_status"
t.string "product_type"
end
In your view, add fields for order_details like:
<%= f.fields_for :order_details do |od| %>
<%= od.label 'your attribute for OrderDetail' %>
<%= # od.text_field 'your attribute' %>
<% end %>
Then in your model, accept nested attributes for order_details
like:
accepts_nested_attributes_for :order_details
These are sample values, you can use this logic with your actual attributes.
In your controller, permit attributes for order_details like:
params.require(:order).permit(:id, :name, order_details: [
#attributes of order details
])
Assuming that product_ids is an array of the product ids that you wish to add to the order, you could try assigning them in the following way and Rails should automagically create those association records for order_details when you then call #order.save
#order.products << Product.find_by_id(product_ids)
Am i right add that rows for controller?
Order_controller:
def create
#order = current_user.orders.new(order_params)
#order.products = Product.find_by_id(order_params[:product_ids])
#order.date = Date.today.to_s
if #order.save
flash[:success] = "Order was successfully submitted"
redirect_to new_order_path
else
render :new
end
end
private
def order_params
params.require(:order).permit(:date, order_details: [:product_id])
end
end
order model:
accepts_nested_attributes_for :order_details
I'm trying to save from 3 different types of products.
But how to take one product id from each part ? Because now I can choose only one product from all
View:
= simple_form_for(#order, html: {:class => 'well form-horizontal', :method => :post, :action=> :create }) do |f|
.col-xs-12.col-sm-6.col-md-8
= render 'shared/error_messages', object: f.object
%br
= simple_fields_for :order_details do |od|
= od.collection_radio_buttons :product_ids, Product.get_first_course, :id, :product_name ,:item_wrapper_class => 'inline'
%hr
= od.collection_radio_buttons :product_ids, Product.get_main_course, :id, :product_name, :item_wrapper_class => 'inline'
%hr
= od.collection_radio_buttons :product_ids, Product.get_drink, :id, :product_name,:item_wrapper_class => 'inline'
%hr
= f.button :submit, class: "btn btn-primary"
I change my association type to HABTM and that's enough for my situation. So..
models:
class Order < ActiveRecord::Base
has_and_belongs_to_many :products
before_destroy { products.clear }
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :orders
end
Order_controller:
def create
order = current_user.orders.new(date: Date.today.to_s)
#order_products = Product.where(id: order_params[:product_ids])
order.products << #order_products
if order.save
#blalblal - sucsess
else
#blabla - alert-notice
end
I am new to rails 4.I used nested attributes for multiple image upload.But i'm having few problems with this
im getting ActiveRecord::StatementInvalid in Products#index
Mysql2::Error: Unknown column 'pictures.product_id' in 'where clause': SELECT pictures. FROM pictures WHERE pictures.product_id = 11* error
My models are as follows
class Picture < ActiveRecord::Base
belongs_to :product
has_attached_file :image
end
class Product < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :comments , dependent: :destroy
has_many :pictures
accepts_nested_attributes_for :pictures
end
products_controller.rb
class ProductsController < ApplicationController
def show
#product = Product.find(params[:id])
#comment = #product.comments.build
#category_id = #product.category_id
#category1 = Category.find_by(id: #category_id)
end
def new
#product = current_user.products.build
#product.pictures.build
end
def create
#product = current_user.Product.new(product_params)
#product.save
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :price, :description, :reason, :user_id,:status,:category_id,pictures_attributes: [:image])
end
def correct_user
#product = current_user.products.find_by(id: params[:id])
redirect_to root_url if #product.nil?
end
end
Schema.rb
ActiveRecord::Schema.define(version: 20151226132302) do
create_table "pictures", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name", limit: 255
t.integer "price", limit: 4
t.text "description", limit: 65535
t.text "reason", limit: 65535
t.integer "user_id", limit: 4
t.string "image_file_name", limit: 255
t.string "image_content_type", limit: 255
t.integer "image_file_size", limit: 4
t.datetime "image_updated_at"
t.string "status", limit: 255
t.integer "category_id", limit: 4
t.integer "product_id", limit: 4
end
end
My migration file
20151226132302_add_product_id_to_product.rb
class AddProductIdToPictures < ActiveRecord::Migration
def change
add_reference :pictures, :product, index: true
end
end
Even with above migration product_id is not added to pictures model.
Can somebody help me with this?
It will be helpful if someone can give me nice reference for RAILS 4
unknown attribute 'product_id'
Suggests you don't have the product_id column in your pictures table.
If you're using has_many / belongs_to, you'll need to set the foreign_key for your belongs_to model in its table:
If you don't have the product_id column in your pictures table, you'll need to use the following:
$ rails g migration AddProductIdToPictures
# db/migrate/add_product_id_to_pictures_________.rb
class AddProductIdToPictures < ActiveRecord::Migration
def change
add_reference :pictures, :product, index: true
end
end
$ rake db:migrate
Ref: Add a reference column migration in Rails 4
Another issue you may have is that you're using .build in the new method. I know that new and build have very little difference, but I was under the impression to use new:
def new
#product = current_user.products.new
#product.pictures.build
end
You've also got an error in your create action:
def create
#NO - #product = current_user.Product.new(product_params) #-> cannot use constant
#Should be this:
#product = current_user.products.new
#product.save
end
i have such model:
class ToType < ActiveRecord::Base
attr_accessible :Name, :TYP_CCM, :TYP_CCM_TAX, :TYP_CDS_ID, :TYP_CTM, :TYP_CYLINDERS, :TYP_DOORS, :TYP_HP_FROM, :TYP_HP_UPTO, :TYP_ID, :TYP_KV_ABS_DES_ID, :TYP_KV_ASR_DES_ID, :TYP_KV_AXLE_DES_ID, :TYP_KV_BODY_DES_ID, :TYP_KV_BRAKE_SYST_DES_ID, :TYP_KV_BRAKE_TYPE_DES_ID, :TYP_KV_CATALYST_DES_ID, :TYP_KV_DRIVE_DES_ID, :TYP_KV_ENGINE_DES_ID, :TYP_KV_FUEL_DES_ID, :TYP_KV_FUEL_SUPPLY_DES_ID, :TYP_KV_MODEL_DES_ID, :TYP_KV_STEERING_DES_ID, :TYP_KV_STEERING_SIDE_DES_ID, :TYP_KV_TRANS_DES_ID, :TYP_KV_VOLTAGE_DES_ID, :TYP_KW_FROM, :TYP_KW_UPTO, :TYP_LA_CTM, :TYP_LITRES, :TYP_MAX_WEIGHT, :TYP_MMT_CDS_ID, :TYP_MOD_ID, :TYP_PCON_END, :TYP_PCON_START, :TYP_RT_EXISTS, :TYP_SORT, :TYP_TANK, :TYP_VALVES, :is_in_to
set_primary_key :TYP_ID
belongs_to :to_model
has_many :to_articles, :dependent => :destroy
end
class ToArticle < ActiveRecord::Base
attr_accessible :details, :manufacturer, :name, :oem_number, :only_with_vin, :quantity, :type_id
belongs_to :to_type
end
(some db is converted from big catalog, so rails conventions are a little bit missed)
my show view of to_type is:
part of it:
%td
= link_to "Подробнее", admin_catalog_to_to_article_path(c), :class=>'btn btn-primary'
= link_to "Редактирование", edit_admin_catalog_to_to_type_path(c), :class=>'btn btn-warning'
= link_to "Удалить", admin_catalog_to_to_type_path(c), :confirm => "!!!Тип #{c.Name} будет удалён!!!! Вы уверены?", :method => :delete, :class => "btn btn-danger"
my show action work normally, also controller:
class Admin::Catalog::To::ToTypesController < ApplicationController
respond_to :html
before_filter :auth_user
def auth_user
redirect_to new_admin_session_path unless admin_signed_in?
end
def show
#mod_id = params[:id]
#man = ToType.find(:all, conditions: {:TYP_MOD_ID => #mod_id}, order: "Name ASC")
render :layout => 'admin'
end
def edit
#man = ToType.find(params[:id])
render :layout => 'admin'
end
def update
#man = ToType.find(params[:id])
if #man.update_attributes(params[:to_type])
redirect_to admin_catalog_to_to_type_path(#man.TYP_MOD_ID)
else
render :layout => 'admin'
end
end
def new
#man = ToType.new
#mod_id = params[:mod_id]
render :layout => 'admin'
end
def create
#man = ToType.new(params[:to_type])
#mod_id = params[:mod_id]
#man.TYP_MOD_ID = #mod_id
if #man.save
redirect_to admin_catalog_to_to_type_path(#mod_id)
else
render :layout => 'admin'
end
end
def destroy
#man = ToType.find(params[:id])
if #man.destroy
redirect_to admin_catalog_to_to_type_path(#man.TYP_MOD_ID)
else
render :layout => 'admin'
end
end
end
and route:
namespace :admin do
namespace :catalog do
namespace :to do
resources :to_manufacturers,
:to_models,
:to_types,
:to_articles
end
end
end
but when i try to call destroy method i get:
ActiveRecord::StatementInvalid in Admin::Catalog::To::ToTypesController#destroy
Mysql2::Error: Unknown column 'to_articles.to_type_id' in 'where clause': SELECT `to_articles`.* FROM `to_articles` WHERE `to_articles`.`to_type_id` = 26923
also when i try edit or create i get:
undefined method `model_name' for NilClass:Class
i think that something is bad with connection with model: with update and create it didn't initialize object.
With destroy it use other! db. What happens?
Also i try to recreate it all and rename, nothing... Could understand what wrong... Also when in model i write which db table to use same errors appear.
when i try to add new object via console all is ok.
upd:
class CreateToTypes < ActiveRecord::Migration
def change
create_table :to_types, :primary_key => :TYP_ID do |t|
t.integer :TYP_ID
t.integer :TYP_CDS_ID
t.integer :TYP_MMT_CDS_ID
t.integer :TYP_MOD_ID
t.binary :TYP_CTM
t.binary :TYP_LA_CTM
t.integer :TYP_SORT
t.integer :TYP_PCON_START
t.integer :TYP_PCON_END
t.integer :TYP_KW_FROM
t.integer :TYP_KW_UPTO
t.integer :TYP_HP_FROM
t.integer :TYP_HP_UPTO
t.integer :TYP_CCM
t.integer :TYP_CYLINDERS
t.integer :TYP_DOORS
t.integer :TYP_TANK
t.integer :TYP_KV_VOLTAGE_DES_ID
t.integer :TYP_KV_ABS_DES_ID
t.integer :TYP_KV_ASR_DES_ID
t.integer :TYP_KV_ENGINE_DES_ID
t.integer :TYP_KV_BRAKE_TYPE_DES_ID
t.integer :TYP_KV_BRAKE_SYST_DES_ID
t.integer :TYP_KV_FUEL_DES_ID
t.integer :TYP_KV_CATALYST_DES_ID
t.integer :TYP_KV_BODY_DES_ID
t.integer :TYP_KV_STEERING_DES_ID
t.integer :TYP_KV_STEERING_SIDE_DES_ID
t.float :TYP_MAX_WEIGHT
t.integer :TYP_KV_MODEL_DES_ID
t.integer :TYP_KV_AXLE_DES_ID
t.integer :TYP_CCM_TAX
t.float :TYP_LITRES
t.integer :TYP_KV_DRIVE_DES_ID
t.integer :TYP_KV_TRANS_DES_ID
t.integer :TYP_KV_FUEL_SUPPLY_DES_ID
t.integer :TYP_VALVES
t.integer :TYP_RT_EXISTS
t.string :Name
t.boolean :is_in_to
t.string :fuel_type
end
end
end
class CreateToArticles < ActiveRecord::Migration
def change
create_table :to_articles do |t|
t.string :oem_number
t.string :manufacturer
t.text :name
t.integer :quantity
t.text :details
t.boolean :only_with_vin
end
end
end
you don't have relationship between ToArticle and ToType in database.
use belongs_to in ToArticle migration
check rails guide on associations