How to connect 2 Models in rails 5


I want the user show page to display the content of the user’s first micropost. I already have user that accepts name and email and micropost that accepts the post and user id. My guess is I need to connect the user of the micropost to the id of user but i don'tknow how.


According to the description in question you should have something like


class User < ActiveRecord::Migration
  has_many :microposts
  # attributes :id, :name, :email


class Micropost < ActiveRecord::Migration
  belongs_to :user
  # attributes :id, :user_id, :post
By : Deepak

What you are looking to do is to make a simple model relation. You can do this by defining the relationship in the relevant model file.

Lets say you wanted to link the post to the user based on a foreign key relationship linking the user_id field on post to the id field on user. In the posts model file, do something like this:

belongs_to :user

That lets ruby know how to structure the queries properly when joining data across models.

By : rikola

I would leverage Hostlistener to do that:

  selector: "[Enter]"
export class Enter {
  @HostListener('document:keyup', ['$event'])
  enter(event) {
    if (event.keyCode !== 13) return;;
  constructor(private el: ElementRef) { }

The handler will be automatically removed in ngOnDestroy

By : yurzui

This video can help you solving your question :)
By: admin