I’m new to Rails and already did some stuff with ActiveRecord
associations but I cannot do one thing:
I’ve got a
class Paragraph < ActiveRecord::Base
end
And I want each Paragraph to contain a list of words (each word is
simply a String). I want to have a table with all Paragraphs and save/
load them. And finally get a json rep of a paragraph. Simple. If I do
class Paragraph < ActiveRecord::Base
has_many :words
end
class Word < ActiveRecord::Base
belongs_to :paragraph
end
and put corresponding stuff in the db schema
create_table “words”, :force => true do |t|
t.integer “paragraph_id”
t.string “content”
end
So, this would work, and a json rep of a paragraph would look like
(stripped some stuff for clarity)
but I don’t want this extra complexity so I want to get something like
{“words”: [“Once”, “upon”, “a”, “time”]}
A plain array of strings without the extra nesting.
But I can’t do
class Paragraph < ActiveRecord::Base
has_many :words, :class_name => “String”
end
without the Word class at all
===
I could add some additional to_json parameters I guess and tweak it to
give me what I want but it’d be ugly.
How do I achieve this with ActiveRecord? I guess a paragraphs_words
join table would work but I can’t work out the details.
This won’t answer your question but I hope it helps you because your
approach sounds too complicated to me, unless it is just for playing
and learning. Why would you want to store each word in a record in a
table? What if a word belongs to more than one paragraph?
end
(stripped some stuff for clarity)
A plain array of strings without the extra nesting.
I could add some additional to_json parameters I guess and tweak it to
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
@pepe:
Yeah, one word could belong to many paragraphs but it was actually
more for experimentation purposes.
With Hibernate in Java one could use annotations like @Embedded to
achieve something similar so I wanted to compare Hibernate and
ActiveRecord but in reality, you’re right, it is a bit too complicated
(:
@Erol
Yep, I guess I’ll end up doing just that (: Just wondered if there is
something neater to do.