I am creating an app using Ruby on Rails and in the Admin panel there are blogs and posts controllers. The routes for the admin area looks like this:
constraints :subdomain => "admin" do
scope :module => "admin" do
root to: "pages#index"
resources :blogs do
resources :posts, :controller => "posts"
end
end
end
What I have is http://admin.mydomain.com/blogs showing the blogs with /blogs/2/ showing the posts on that blog.
What I want is for when creating a new post at /blogs/2/posts/new that the blog_id is attached to the post.
In the admin/posts_controller.rb I have this as the 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 just creates a post. I want to link that post to the current blog id which is in the URL – /blog/2.
How would I go about doing this?
There are a number of ways of doing this and does depend on how you’re actually using the controller. If you just edit posts at /blogs/1/xxxx then you can do this:
The blog_id will be available as
params[:blog_id]. I’d usually create a before_filter to find the blog and then do the rest in the create action: