I'm making a simple association between 2 models, Author and Story.
class Story < ActiveRecord::Base
validates :category_id, presence: {message: "Se debe escoger una categoría"}
validates :cuento, presence: {message: "Debe tener algun relato para ingresar"}
validates :nombre, presence: {message: "No se puede ingresar relato sin titulo"}
belongs_to :author, class_name: "Author", :primary_key=>"id", :foreign_key => "author_id"
end
class Author < ActiveRecord::Base
has_many :stories, :class_name => "Story", :primary_key => "id", :foreign_key =>"author_id"
end
And in the schema:
create_table "authors", force: true do |t|
t.string "nombre"
t.date "bod"
t.string "pais"
t.string "ciudad"
t.datetime "created_at"
t.datetime "updated_at"
t.text "bio"
t.integer "user_id"
end
create_table "stories", force: true do |t|
t.string "nombre"
t.integer "category_id"
t.date "fecha"
t.datetime "created_at"
t.datetime "updated_at"
t.text "resumen"
t.text "cuento"
t.integer "author_id"
end
add_index "stories", ["author_id"], name: "index_stories_on_author_id", using: :btree
Now, if I do a simple query on the console, like:
Author.joins(:stories)
And this returns:
ActiveRecord::ConfigurationError: Association named 'stories' was not found on Author; perhaps you misspelled it?
What can be causing problems with this query?
UPDATE: I added the suggestion:
class Author < ActiveRecord::Base has_many :stories, class_name: "Story" end class Story < ActiveRecord::Base belongs_to :author, class_name: "Author" end But, in the console looks the same error :(
'ActiveRecord::ConfigurationError: Association named 'stories' was not found on Author; perhaps you misspelled it?' Some other ideas???' Thanks!
UPDATE 2 I make a change in the model code adding the suggestion of put the optionals class_name, foreign_key, primary_key, and still nothing ...
:authors
table have an:id
column? looks like you have:user_id
in there as well, is:user_id
a foreign_key or primary_key for:authors
table? – Firyn:class_name
,:foreign_key
, and:primary_key
– Firyn