Answer the question
In order to leave comments, you need to log in
How to make a user-post-comment association?
I want to try to make the user-post-comment.post-comments association work, I figured it out. But what else would it all be tied to the user, I don’t understand. As I understand it, you need to add some kind of rule to the database and fix the action in posts controller and view. But I don't know what
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
post = Post.new
end
def create
post = Post.new(post_params)
post.save
redirect_to post
end
def update
post = Post.find(params[:id])
if post.update(post_params)
redirect_to post
else
render 'edit'
end
end
def show
post = Post.find(params[:id])
end
def destroy
post = Post.find(params[:id])
post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
Answer the question
In order to leave comments, you need to log in
If you do this from the very beginning, everything will work.
user.rb
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
...
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name)
end
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class PostsController < ApplicationController
...
def post_params
params.require(:post).permit(:title, :body, :user_id)
end
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class PostsController < ApplicationController
...
def post_params
params.require(:post).permit(:body, :user_id, :post_id)
end
end
What's with the post controller? Something tells me that I need to CommentController::create
add CommentController::update
something similar to Comment.user = current_user
before saving. Although I may not be right.
or immediately create from links, there are many options
def create
post = current_user.posts.create(post_params)
redirect_to post
end
def create
post = current_user.posts << Post.create(post_params)
redirect_to post
end
def create
transaction do
post = Post.create(post_params)
post.user = current_user
post.save
end
redirect_to post
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question