I created one has_many through relationship in rails api. I also used nested routes.
My models like below;
class Author < ActiveRecord::Base
has_many :comments
has_many :posts, :through => :comments
end
class Post < ActiveRecord::Base
has_many :comments
has_many :authors, :through => :comments
end
class Comment < ActiveRecord::Base
belongs_to :author
belongs_to :post
end
my routes like below;
Rails.application.routes.draw do
namespace :api, defaults: { :format => 'json' } do
resources :posts do
resources :comments
end
resources :authors
end
end
So here my aims are
- Comments are nested route so that i can create and display comments from post
- Here not any post author. The author is meant for comment owner
I implemented the concepts and working almost all. But i am facing the following 2 problems with associations
- How to add additional fields for associated table when parent create. Here my requirement is when a post is created, i need to insert one default entry for comment. My post controller implementation for create is like below
def create params = create_params.merge(:record_status => 1) @post = Post.new(params) @post.authors << Author.find(1) if @post.save render :show, status: :created end end def show @post = Post.find(params[:id]) end private def create_params params.permit(:name, :description, :author_id ) end
Here i am passing author_id in the request json. This needs to be added as author id in the comments table. Now i just hard coded as 1. I used '<<' for association entry. This is working but i also need to include two more fields which are :comments and :record_status. Again :comments is from the request itself.
Note: This is not rails mvc application. This is rails api and input as json.
- When i display comments using nested routes i need to show author and also comments from comments table. My comments controller method is ;
class Api::CommentsController < ApplicationController before_filter :fetch_post def index @authors = @post.authors.where(:record_status => 1, comments: { record_status: 1 }) end private def fetch_post @post = Post.find(params[:post_id]) end end
Here i got authors but not correct comments in the join table 'comments'
Please help me to solve these issues