質問編集履歴

2

postとtagを追記

2018/01/18 11:05

投稿

you88
you88

スコア147

test CHANGED
File without changes
test CHANGED
@@ -51,3 +51,65 @@
51
51
  end
52
52
 
53
53
  ```
54
+
55
+
56
+
57
+ ```
58
+
59
+ class Post < ApplicationRecord
60
+
61
+ has_many :tag_maps, dependent: :destroy
62
+
63
+ has_many :tags, through: :tag_maps
64
+
65
+
66
+
67
+ def save_posts(savepost_tags)
68
+
69
+ current_tags = self.tags.pluck(:name) unless self.tags.nil?
70
+
71
+ old_tags = current_tags - savepost_tags
72
+
73
+ new_tags = savepost_tags - current_tags
74
+
75
+
76
+
77
+ # Destroy old taggings:
78
+
79
+ old_tags.each do |old_name|
80
+
81
+ self.tags.delete Tag.find_by(name:old_name)
82
+
83
+ end
84
+
85
+
86
+
87
+ # Create new taggings:
88
+
89
+ new_tags.each do |new_name|
90
+
91
+ post_tag = Tag.find_or_create_by(name:new_name)
92
+
93
+ self.tags << post_tag
94
+
95
+ end
96
+
97
+ end
98
+
99
+ end
100
+
101
+ ```
102
+
103
+ ```
104
+
105
+ class Tag < ApplicationRecord
106
+
107
+ validates :name,presence:true,length:{maximum:50}
108
+
109
+ has_many :posts, through: :tag_maps
110
+
111
+ has_many :tag_maps, dependent: :destroy
112
+
113
+ end
114
+
115
+ ```

1

tag_mapのmodel記述

2018/01/18 11:05

投稿

you88
you88

スコア147

test CHANGED
File without changes
test CHANGED
@@ -33,3 +33,21 @@
33
33
 
34
34
 
35
35
  kaminariで抽出するpostに条件をつけたい場合、どうすればいいんでしょうか?
36
+
37
+
38
+
39
+ ```
40
+
41
+ class TagMap < ApplicationRecord
42
+
43
+ belongs_to :post
44
+
45
+ belongs_to :tag
46
+
47
+ validates :post_id,presence:true
48
+
49
+ validates :tag_id,presence:true
50
+
51
+ end
52
+
53
+ ```