먼저이 문제를 해결하기 위해 데이터베이스를 설정해야합니다. has_and_belongs_to_many에 비해 유연성이 높기 때문에 개인적으로 has_many : with association을 사용합니다. 그러나 선택은 당신에게 달려 있습니다. API에서 여러 유형을 찾아보고 스스로 결정하는 것이 좋습니다. 이 예제는 has_many : through를 다룰 것이다.
모델
# user.rb (model)
has_many :favorites
has_many :posts, :through => :favorites
# post.rb (model)
has_many :favorites
has_many :users, :through => :favorites
# favorite.rb (model)
belongs_to :user
belongs_to :post
컨트롤러
# favorites_controller.rb
def create
current_user.favorites.create(:post_id => params[:post_id])
render :layout => false
end
경로
match "favorites/:post_id" => "favorites#create", :as => :favorite
jQuery를
$(".favorite").click(function() {
var post_id = $(this).attr('id');
$.ajax({
type: "POST",
url: 'favorites/' + post_id,
success: function() {
// change image or something
}
})
})
노트
이것은 몇 가지 가정 : jQuery를 사용하여 레일 (3)는, 각각 마음에 드는 아이콘이 포스트 ID로 html로 ID가 있습니다. 코드를 테스트하지 않았고이 창에서 작성 했으므로 약간의 사소한 문제를 해결해야하지만 실제로는 이 어떻게 수행되는지에 대한 인상을 주어야합니다. 시각적 인 물건들과 그런 것들은 당신에게 달려 있습니다.
누군가 실수를 저지른 경우이 게시물을 편집하십시오.