Reputation: 21
i want to ask about activating selected post as representative post
what if i have two model
class Blog < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :blog
end
and each model has following columns
create_table "blogs", force: :cascade do |t|
t.string "title"
t.boolean "main_post_yn"
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.integer "blog_id"
end
and if user enter main_post_yn as true, i want to show selected single post.
so i thought...
create_table "blogs", force: :cascade do |t|
t.string "title"
t.boolean "main_post_yn"
t.integer "post_id"
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.integer "blog_id"
end
i add post_id to blog model.
and i though following flow.
i think upper process isn't rails way. do you have any advise?
thanks.
Upvotes: 0
Views: 35
Reputation: 18647
Since you have Blog has_many :posts
and Post belongs_to :blog
Don't, add post_id
in Blog table
.
class Blog < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :blog
end
create_table "blogs", force: :cascade do |t|
t.string "title"
t.boolean "main_post_yn"
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.integer "blog_id"
end
Now, In the controller,
blogs = Blog.where(main_post_yn: true) // get all blogs with `main_post_yn` as true
@post_ids = []
blogs.each do |blog|
@post_ids << blog.posts.pluck(:id) // push post-Id's of those blogs into an array
end
@posts = Post.where(id: @post_ids) // get all posts with those post-Id's
show all posts which belongs to blog. got fulfilled.
Upvotes: 0