I have a model "Post" which belongs_to "Group." The url is like this .../groups/26/posts/1 everything was working fine until I needed to add a user name to each post so I added a new foreign key to the Posts table for "User" and made the Post model belongs_to :user, and in the User model added has_many :posts.
My issue is that I don't know how to create a new post so that I can get both the group_id and user_id added to the posts table.
This works to populate the user_id foreign key of the Posts table. I need to call group in here somehow but can't make it work.
def new
@posts = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Post created successfully!"
redirect_to group_url(@post.group)
else
render 'new'
end
end
This works to populate the group_id foreign key of the Posts table, I would need to call @user or current_user in here somehow but not sure how to do it.
# GET /groups/:group_id/posts/new
def new
@posts = @group.posts.new
end
def create
@post = @group.posts.new(post_params)
if @post.save
flash[:success] = "Post created successfully!"
redirect_to group_url(@post.group)
else
render 'new'
end
end