I wanted to make an article posting app with Rails, and when I introduced Scaffold to cut the procedure, I stumbled on connecting posts and users, so I shared my knowledge If you want to know more, please see this document.
First, generate a posting function with Scaffold. Insanely easy. db: migrate Don't forget
$ rails g scaffold Post content:string
$ db:migrate
devise Refer to this article. Very easy to understand
app/models/user.rb
class User < ApplicationRecord
#Add the following.Don't forget the plural s
has_many :posts, dependent: :destroy
end
app/models/post.rb
class Tip < ApplicationRecord
#Add the following.To be on the safe side, make sure empty posts are rejected
belongs_to :user
validates :content, presence: true
end
$ rails g migration add_user_id_to_posts user_id:integer
$ rails db:migrate
*** This completes the link between the User model and the Post model in terms of mechanism ***
app/controllers/posts_controller.rb
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Only allow a list of trusted parameters through.
def post_params
params.require(:post).permit(:content)
end
end
Modify the above code automatically generated by Scaffold as follows.
app/controllers/posts_controller.rb
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Only allow a list of trusted parameters through.
def post_params
params.require(:post).permit(:content).merge(user_id: current_user.id)
end
end
This completes. Let's run it, go to localhost: 3000 / posts and post it! ‼
Recommended Posts