lee
lee

Reputation: 21

About rails activating post

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.

  1. user click "main_post_yn" true.
  2. show all posts which belongs to blog.
  3. user select single post and pass it's id to Blog.post_id
  4. at main page, pass "Post.id = Blog.post_id" in controller and show it as representative post

i think upper process isn't rails way. do you have any advise?

thanks.

Upvotes: 0

Views: 35

Answers (1)

Sravan
Sravan

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

Related Questions