如何在rails中创建之前获取正确的id

时间:2016-05-10 02:42:12

标签: ruby-on-rails ruby ruby-on-rails-4

我正在扩展M.Hartl的Sample twitter应用程序。

我所做的是创建一个名为Books的新模型。我希望这些图书可以像用户一样关注,因此,如果您关注图书,则会在Feed中看到与该图书相关的所有评论。

我在创建模型方面取得了一些成功,并且遵循了它。我可以按照这本书,用id“2”说,并在帖子中显示帖子。虽然当我尝试follow a user with id 2时,我最终会following book id "2"或在我的控制台中获得UNIQUE constraint failed。另一件奇怪的事情,如果我用book和id“2”破坏关系并且只关注用户“2”,我实际上得到了用户帖子,虽然我无法取消关注用户的按钮,但我必须去预订“2”并从那里取消。

有什么想法吗?

我想我需要在我的.create中进行if else检查,以确保我是否在书页上我在关注书籍而不是用户之前提交数据库。

任何帮助或想法将不胜感激。

这是一些相关的代码:

 class User < ActiveRecord::Base
 def feed
following_ids_subselect = "SELECT followed_id FROM relationships
                           WHERE  follower_id = :user_id"
Micropost.where("book_id IN (#{following_ids_subselect})
                 OR user_id = :user_id", user_id: id)
end


# Follows a user.
   def follow(other_user)
   active_relationships.create(followed_id: other_user.id)
  end

# Follows a book.
   def follown(book)
   active_relationships.create(followed_id: book.id)
  end

# Unfollows a user.
   def unfollow(other_user)
   active_relationships.find_by(followed_id: other_user.id).destroy
  end

# Unfollows a book.
  def unfollown(book)
  active_relationships.find_by(followed_id: book.id).destroy
  end

# Returns true if the current user is following the other user.
   def following?(other_user)
   following.include?(other_user)
  end

# Returns true if the current user is following the book.
   def followingn?(book)
   following.include?(book)
  end


 class RelationshipsController < ApplicationController
 def create
  @user = User.find(params[:followed_id])
  if current_user.follow(@user)
  else 
    @book = Book.find(params[:followed_id])
    current_user.follown(@book)
  end
# respond_to do |format|
#   format.html { redirect_to @user }
#   format.js 
# end
end


class Relationship < ActiveRecord::Base
 belongs_to :follower, class_name: "User"
 belongs_to :followed, class_name: "User"
 belongs_to :followed, class_name: "Book"

 validates :follower_id, presence: true
 validates :followed_id, presence: true
end

0 个答案:

没有答案