I am working on a simple app that allows a user to write a post (parent_post), and another user to answer this post (child_post). I am using the Ancestry gem to track the relationships between the posts. Ancestry is a gem/plugin that allows the records of a model to be organised as a tree structure (or hierarchy). It exposes all the standard tree structure relations (parent, root, children, ancestors...).
The database schema.rb of the app:
create_table "posts", :force => true do |t|
t.text "title"
t.text "content"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
t.string "ancestry"
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "name"
end
The challenge: I want to display informations about the author of the parent_post in the show view of a child_post . Via the Ancestry gem you can call for "parent" and address all the columns inside of the posts table. The posts table (see above) has a user_id column, so I can call
@post.parent.user_id
to show me the User ID, which works. But I would like to show the username instead of the user_id.
Of course, user_id and username (name) are via the users table connected (see schema.rb above), but how can I address them here? @post.parent.user_id.name is not working.
The models:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
has_ancestry
belongs_to :user
end
I am still quite new to Rails and stuck here. Is there maybe a super easy solution I am not seeing?
Thank you so much for helping out!
How about @post.parent.user.name? I recommend making this a method on the Post model rather than your view or controller. Call it @post.original_poster_name or similar.