#Rails How to retrieve data item from ActiveStorage::Blobs table? - ruby-on-rails

I need retrieve names of the files stored in blobs table of ActiveStorage. I cannot find a working way to do so.
FloorPlan.rd model file :
class FloorPlan < ApplicationRecord
belongs_to :unit
has_many_attached :floor_image, dependent: :destroy
validates :name, presence:true
validates :floor_image, presence:true
end
And here is the snippet from schema.rb
create_table "floor_plans", force: :cascade do |t|
t.string "name", null: false
t.bigint "unit_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["unit_id"], name: "index_floor_plans_on_unit_id"
end
A part of Unit.rb model file :
class Unit < ApplicationRecord
has_many :floor_plans, dependent: :delete_all
Need to print the name of :floor_image file. Like if the name is floor.png then output should be this name.
Here is the image showing floor_plans table
Here is attachments table
Here is the blobs table from where I want print the filename for eg. "sample.jpg1".
I tried to implement from this answer
But no help in a data entry getting returned :(

Related

Creating Custom Friendship Associations Based Around an "Event" Model

I've been researching friendship models using roles, custom associations, etc. But I haven't been able to connect my project to the concepts in a clear way.
I want a "User" to be able to create an event I'm calling a "Gather". A User can also attend a Gather created by other Users. By attending a Gather, the "User" can also be a "Gatherer".
The list of Gatherers will technically be considered friends of the "creator". This is how far I've gotten:
Models:
User
Gather
Gatherer (?)
User
class User < ApplicationRecord
has_many :gathers_as_creator,
foreign_key: :creator_id,
class_name: :Gather
has_many :gathers_as_gatherer,
foreign_key: :gatherer_id,
class_name: :Gather
end
Gather
class Gather < ApplicationRecord
belongs_to :creator, class_name: :User
belongs_to :gatherer, class_name: :User
end
My question is, do I need to a join table, such as Gatherer, to allow multiple attendees and then later pull a friend list for the user/creator ?
Gatherer
belongs_to :gather_attendee, class_name: "User"
belongs_to :attended_gather, class_name: "Gather"
Here's what I think that schema would look like:
create_table "gatherers", force: :cascade do |t|
t.bigint "attended_gather_id"
t.bigint "gather_attendee_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["attended_gather_id"], name: "index_gatherers_on_attended_gather_id"
t.index ["gather_attendee_id"], name: "index_gatherers_on_gather_attendee_id"
end
Help, my head is spinning trying to understand the connections and how to proceed.
Previous planning:
Schema:
create_table "activities", force: :cascade do |t|
t.string "a_type"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "gatherers", force: :cascade do |t|
t.bigint "attended_gather_id"
t.bigint "gather_attendee_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["attended_gather_id"], name: "index_gatherers_on_attended_gather_id"
t.index ["gather_attendee_id"], name: "index_gatherers_on_gather_attendee_id"
end
create_table "gathers", force: :cascade do |t|
t.integer "creator_id"
t.integer "activity_id"
t.text "gather_point"
t.boolean "active"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "interest_gathers", force: :cascade do |t|
t.string "gather_id"
t.string "interest_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "interests", force: :cascade do |t|
t.string "i_type"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "img"
t.string "first_name"
t.string "last_name"
t.string "state"
t.string "city"
t.string "bio"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
add_foreign_key "gatherers", "gathers", column: "attended_gather_id"
add_foreign_key "gatherers", "users", column: "gather_attendee_id"
end
class User < ActiveRecord::Base
has_many :gatherers, foreign_key: gather_attendee_id
has_many :attended_gathers, through: :gatherers
has_many :created_gathers, foreign_key: :creator_id, class_name: "Gather"
end
class Gather < ActiveRecord::Base
has_many :gatherers, foreign_key: :attended_gather_id
has_many :attendees, through: :gatherers, source: :gather_attendee
belongs_to :creator, class_name: "User"
end
class Gatherer < ActiveRecord::Base
belongs_to :gather_attendee, class_name: "User"
belongs_to :attended_gather, class_name: "Gather"
end
The naming here is not great. When naming your models choose nouns as models represent the actual things in your buisness logic - choosing verbs/adverbs makes the names of your assocations very confusing.
class User < ApplicationRecord
has_many :gatherings_as_creator,
class_name: 'Gathering',
foreign_key: :creator_id
has_many :attendences
has_many :gatherings,
through: :attendences
end
# think of this kind of like a ticket to an event
# rails g model Attendence user:references gathering:references
class Attendence < ApplicationRecord
belongs_to :user
belongs_to :gathering
end
# this is the proper noun form of gather
class Gathering < ApplicationRecord
belongs_to :creator,
class_name: 'User'
has_many :attendences
has_many :attendees,
though: :attendences,
class_name: 'User'
end
My question is, do I need to a join table, such as Gatherer, to allow multiple attendees and then later pull a friend list for the user/creator ?
Yes. You always need a join table to create many to many assocations. Gatherer is a pretty confusing name for it though as that's a person who gathers things.
If you want to get users attending Gatherings created by a given user you can do it through:
User.joins(attendences: :groups)
.where(groups: { creator_id: user.id })
You're on the right track.
If I understand what you're looking for correctly, you want a Gather to have many Users and a User to have many Gathers (for the attending piece). So you need a join table like this (this is similar to your gatherers table, but is in a more conventional Rails style):
create_join_table :gathers, :users do |t|
t.index [:gather_id, :user_id]
t.index [:user_id, :gather_id]
end
And then you'd want your User model to be like this:
class User < ApplicationRecord
has_many :gathers_as_creator, foreign_key: :creator_id, class_name: "Gather"
has_and_belongs_to_many :gathers
end
class Gather < ApplicationRecord
belongs_to :creator, class_name: "User"
has_and_belongs_to_many :users
end
(You can change the name of that :users association if you really want, by specifying extra options -- I just like to keep to the Rails defaults as much as I can.)
That should be the bulk of what you need. If you want to pull all the friends of a creator for a specific gather, you would just do gather.users. If you want to pull all of the friends of a creator across all their gathers, that will be:
creator = User.find(1)
friends = User.joins(:gathers).where(gathers: { creator: creator }).all

Associations within Rails Engine not working

I'm building my first Rails engine and getting pretty confused already defining the associations between two models. For the reason of ease, let's say the name of the engine is Blorg, having two models Article and Author.
blorgh/article.rb
module Blorgh
class Article < ApplicationRecord
belongs_to :author, class_name: 'Blorg::Author',
foreign_key: 'blorg_author_id', optional: true
blorgh/author.rb
module Blorgh
class Author < ApplicationRecord
has_many :articles, class_name: 'Blorg::Article'
schema
create_table "blorgh_authors", force: :cascade do |t|
t.string "name"
t.boolean "inactive", default: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
create_table "blorgh_articles", force: :cascade do |t|
t.string "title"
t.bigint "blorgh_author_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["blorgh_author_id"], name: "index_blorgh_article_on_author_id"
If I try to create an article or count the articles of an author via rails c, I get those errors:
article = Blorgh::Article.new(title: 'New Article')
article.save # expect true
# ==> NoMethodError: private method `attribute' called for #<Blorgh::Article:0x00007fdc3fad4d50>
author = Blorgh::Author.create # worked
author.articles.count # expect 0
# ==> ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column blorgh_articles.author_id does not exist
Does anyone know how I can achieve those in-engine associations correctly?
The second error ("column blorgh_articles.author_id does not exist") is because Rails assumes the foreign key on a has_many relationship is classname_id, which is author_id in your example. You correctly set the foreign key on the belongs_to side, but you need to specify on both sides of the relationship. So:
module Blorgh
class Author < ApplicationRecord
has_many :articles, class_name: 'Blorg::Article', foreign_key: 'blorg_author_id'
...

Why is my Rails activerecord many-to-many through relationship not working

Three models Professor, Expertise & ExpertisesProfessor (the join table). I would like to use a has_many activerecord structure but when I call Expertise.professors.all I get an error
*NoMethodError (undefined method `professors' for Class:0x000000000a1ddda0) *
I want to be able to call Expertise.professors and Professor.expertise ???
I am comfortable with using HABTM instead of "has_many through" but for my project I prefer to use the the " has_many through " relationship so please if I could get solutions along those lines only if possible .
**professor.rb**
class Professor < ApplicationRecord
has_many :expertise_professors
has_many :expertises, through: :expertise_professors
end
**expertise.rb**
class Expertise < ApplicationRecord
has_many :expertise_professors
has_many :professors, through: :expertise_professors
end
**expertises_professor.rb**
class ExpertisesProfessor < ApplicationRecord
belongs_to :expertise
belongs_to :professor
end
My Schema File
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_12_18_191008) do
create_table "expertises", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "expertises_professors", id: false, force: :cascade do |t|
t.integer "expertise_id", null: false
t.integer "professor_id", null: false
end
create_table "professors", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
Any ideas what I have missed ?
You can not call Expertise.professors. You first need to load the single record or object of the Expertise like
expertise = Expertise.first
And then you can get all professors
expertise.professiors.all
Same way you can get all expertises for specific professor.

unknown attribute with polymorphic association

In my online shop I have tables Product and Size, also I think I need to add a table Restocking
Instead of updating a product, I guess It's better to have a Restocking table then I could track the dates where I added any new sizes, quantity, and why not the new prices (buying and selling)... and create stats...
Do you this it is correct?
Once a Restocking is created, the corresponding Product is updated with new quantity and price?
Well,
So it started this way:
#Product
has_many :sizes
accepts_nested_attributes_for :sizes, reject_if: :all_blank, allow_destroy: true
#Size
belongs_to :product
The Restocking table needs to have sizes attributes (like product)
I believe that I have to use polymorphic associations, but how I am supposed to update my schema , what should I add, remove?
So since I added the Restocking model, my models look like this:
#Product
has_many :sizes, inverse_of: :product, dependent: :destroy, as: :sizeable
has_many :restockings
accepts_nested_attributes_for :sizes, reject_if: :all_blank, allow_destroy: true
#Restocking
has_many :sizes, as: :sizeable
belongs_to :product
accepts_nested_attributes_for :sizes, reject_if: :all_blank, allow_destroy: true
#Size
belongs_to :product
belongs_to :restocking
belongs_to :sizeable, polymorphic: true, class_name: "Size"
schema.rb
create_table "sizes", force: :cascade do |t|
t.string "size_name"
t.integer "quantity"
t.bigint "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "quantity_stock"
t.index ["product_id"], name: "index_sizes_on_product_id"
end
create_table "restockings", force: :cascade do |t|
t.bigint "product_id"
t.bigint "sizeable_id"
t.decimal "price", precision: 10, scale: 2
t.decimal "buying_price", precision: 10, scale: 2
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_restockings_on_product_id"
t.index ["sizeable_id"], name: "index_restockings_on_sizeable_id"
end
create_table "products", force: :cascade do |t|
t.string "title", limit: 150, null: false
t.text "description"
t.bigint "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "color"
t.integer "user_id"
t.json "attachments"
t.string "brand"
t.string "ref"
t.decimal "price"
t.decimal "buying_price", precision: 10, scale: 2
t.index ["category_id"], name: "index_products_on_category_id"
end
At this point I have several errors, like
in ProductsController
def new
#product = Product.new
#product.sizes.build
end
error:
ActiveModel::UnknownAttributeError at /admin/products/new
unknown attribute 'sizeable_id' for Size.
Can you light me on the migrations I have to change?
Suggestions are welcome
You're almost there, to use polymorphic inside your Size model, you have to change the size resource, and add two attributes to the resource: sizeable_id and sizeable_type.
The sizeable_type is a string, indicates the class of the parent element, in your case, can be Product or Restocking, and sizeable_id indicates the element_id to find the parent element, your relations are correct, but you must add this elements to your Size, see the following:
One exemple of a migration to your case:
class AddSizeableToSize < ActiveRecord::Migration
def change
add_reference :sizes, :sizeable, polymorphic: true, index: true
end
end
On your Size model:
# app/models/size.rb
class Size < ActiveRecord::Base
belongs_to :sizeable, polymorphic: true
end
In your Product or Restocking model:
has_many :sizes, as: :sizeable
This is just a simple way to make your case works! If you want to know more about rails associations and polymorphism, can take a look in this link.

Rails 5.1.5: TypeError: can't cast ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data

I'm getting a database ROLLBACK with this error in development when I try to update a Puzzle object's User object through the Rails console:
TypeError: can't cast ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data
This only happens when I attempt to use update (or save after something like puzzle.user = some_user). Adding the initial owner commits to the database without issue.
Here are the models in the schema:
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "location_id"
end
create_table "puzzles", force: :cascade do |t|
t.string "name"
t.integer "pieces"
t.integer "missing_pieces"
t.string "previous_owners", array: true
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
And here are the puzzle.rb and user.rb files so far:
class User < ApplicationRecord
validates :username, presence: true
validates :email, presence: true#, uniqueness: true
# use bcrypt for password security
has_secure_password
has_many :puzzles
has_many :reviews
belongs_to :location
end
class Puzzle < ApplicationRecord
validates :name, uniqueness: true
validates :pieces, presence: true, numericality: { only_integer: true }
belongs_to :user
has_many :puzzle_tags
has_many :tags, through: :puzzle_tags
has_many :reviews
delegate :location, to: :user
end
Any idea what could be causing the issue?
***Please note: I'm a newbie and using PostgreSQL for the first time. I specifically chose Postgres as my development database instead of SQLite3 because it allows for array data types. Thanks!
You have previous_owners set up as a string array, but you are pushing integers into it. ActiveRecord is good at casting strings to integers and vice versa normally, but as of Rails 5.1.5, that functionality doesn't work in array fields.
Try using a migration to change the field to an integer array. You'll need to do:
$ rails g migration change_previous_owners_to_integer_array
Then edit the resulting migration file like this:
def change
remove_column :puzzles, :previous_owners, :string, array: true
add_column :puzzles, :previous_owners, :integer, array: true
end

Resources