Rails method for assembling nested resources with blogs and posts

I am creating an application using Ruby on Rails and the admin panel has controllers blogs

and posts

. The routes for the admin area are as follows:

constraints :subdomain => "admin" do
  scope :module => "admin" do
    root to: "pages#index"
    resources :blogs do
      resources :posts, :controller => "posts"
    end
  end
end

      

I have http://admin.mydomain.com/blogs

showing blogs with /blogs/2/

showing posts on this blog.

I want to be /blogs/2/posts/new

attached blog_id

to the message when I create a new post.

Q admin/posts_controller.rb

i have it as create action

def create
  @post = Post.new(params[:post])

  if @post.save
    redirect_to posts_path, notice: 'Post was successfully created.'
  else
    render action: "new"
  end
end

      

At the moment it is just creating a message. I want to associate this post with the current blog id which is in the url - /blog/2

.

How should I do it?

+3


source to share


2 answers


There are several ways to do this, depending on how you actually use the controller. If you are just editing posts in / blogs / 1 / xxxx, you can do this:

Blog_id will be available as params[:blog_id]

. I usually create a before_filter file to find the blog and then do the rest in the create action:



before_filter do
  @blog = Blog.find(params[:blog_id])
end

def create
  @post = @blog.posts.build(params[:post])
  if @post.save
    redirect_to [@blog, @post], notice: 'Post created successfully'
  else
    render :action => 'new'
  end
end

      

+3


source


You want to use ActiveRecord's association permissions for this, something like this should work:

def create
  @blog = Blog.find_by_id(params[:id])

  if @blog
    @post = @blog.posts.new(params[:post])
    if @post.save
      redirect_to posts_path, notice: 'Post was successfully created.'
    end
  end

  render :new  
end 

      



First, find a blog post that according to your route will be: id in the hash parameter. Then use @blog.posts.new

to create a new record associated with this block.

+2


source







All Articles