I am making an app with User, Submissions and Comments. I need both the submissions and comments to have a Like button, so after some researching I finally created a Like model, using the reference to user and a polimorphic reference to Submission and Comment. As I am new in RoR, I share the code I have so you can correct me if there is something wrong:
guser.rb:
class Guser < ActiveRecord::Base
has_many :likes, dependent: :destroy
end
like.rb:
class Like < ActiveRecord::Base
belongs_to :guser
belongs_to :likeable, polymorphic: true
end
submission.rb:
class Submission < ActiveRecord::Base
belongs_to :guser
has_many :comments
...
has_many :likes, as: :likeable
has_many :likers, through: :likes, source: :user
end
comment.rb:
class Comment < ActiveRecord::Base
...
has_many :likes, as: :likeable
has_many :likers, through: :likes, source: :user
end
migration create_likes:
class CreateLikes < ActiveRecord::Migration
def change
create_table :likes do |t|
t.integer :likeable_id
t.string :likeable_type
t.references :guser, index: true, foreign_key: true
t.timestamps null: false
end
end
end
Now my question is: I need to only show the like button if the submission/comment has not been already liked by the user. So now I need to do something like this:
<%if current_guser and not current_guser.likes.map(&:submission_id).include? submission.id %>
<%= link_to(image_tag("http://ift.tt/1SB1yKg", :width => 8, :height => 8), { :controller => "likes", :submission_id => submission.id,:action => "create"}, method: :post) %>
But now I need to check if the likeable_type is submission and the likeable_id matches with the submission id. And, in the comments view I must do the same but with the comments. How can I do this check? Is there any includes function for a map with more than one attribute?
Thank you!
Aucun commentaire:
Enregistrer un commentaire