You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
has_many:likes,dependent: :destroy# because the following line uses like_questions, which is not standard naming convention# must include "source: :question" for rails to know that liked_questions is actually questionhas_many:liked_questions,through: :likes,source: :question
and the like model should have the following association:
belongs_to:userbelongs_to:question
test association in rails console:
2.2.3 :001 > u = User.last
User Load (0.8ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
+----+----------+----------+----------+----------+---------+----------+-------+
| id | first... | last_... | email | passw... | crea... | updat... | admin |
+----+----------+----------+----------+----------+---------+----------+-------+
| 12 | William | Wang | willi... |$2a$1... | 2016... | 2016-... |false|
+----+----------+----------+----------+----------+---------+----------+-------+
1 row inset
2.2.3 :002 > q = Question.last
Question Load (2.3ms) SELECT "questions".* FROM "questions" ORDER BY "questions"."id" DESC LIMIT 1
+-----+---------+---------+---------+----------+----------+---------+---------+
| id | title | body | crea... | updat... | view_... | cate... | user_id |
+-----+---------+---------+---------+----------+----------+---------+---------+
| 522 | Will... | How ... | 2016... | 2016-... | 5 | 5 | 12 |
+-----+---------+---------+---------+----------+----------+---------+---------+
1 row inset
the above is to set u and q as user and question.
there are 3 ways to create many to many associations in the database:
2.2.3 :003 > u.liked_questions << q
(0.1ms) BEGIN
SQL (1.2ms) INSERT INTO "likes" ("user_id", "question_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["user_id", 12], ["question_id", 522], ["created_at", "2016-02-18 21:11:39.741137"], ["updated_at", "2016-02-18 21:11:39.741137"]]
(6.1ms) COMMIT
Question Load (1.2ms) SELECT "questions".* FROM "questions" INNER JOIN "likes" ON "questions"."id" = "likes"."question_id" WHERE "likes"."user_id" = $1 [["user_id", 12]]
+-----+---------+---------+---------+----------+----------+---------+---------+
| id | title | body | crea... | updat... | view_... | cate... | user_id |
+-----+---------+---------+---------+----------+----------+---------+---------+
| 522 | Will... | How ... | 2016... | 2016-... | 5 | 5 | 12 |
+-----+---------+---------+---------+----------+----------+---------+---------+
1 row in set