我使用此代码时遇到错误。
def create
new_post
@post.save!
(@post.users.uniq - [current_user]).each do |user|
Notification.create(recipient: user, actor:current_user, action: "posted", notifiable: @post)
end
redirect_to post_index_path
end
我不确定为什么会出现错误,但错误消息显示我使用“user”而不是“users”但我不能使用uniq这样做。我也犯了更多错误。
编辑: 这是我的帖子模型:
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
belongs_to :subject
validates_presence_of :content
end
我也有一个科目模型:
class Subject < ActiveRecord::Base
has_many :posts
has_many :users, through: :posts
validates_presence_of :name
validates_uniqueness_of :name
end
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :name, presence: true
has_many :listings, dependent: :destroy
has_many :purchasing, class_name: "Transaction", foreign_key: "buyer_id", dependent: :destroy
has_many :sell, class_name: "Transaction", foreign_key: "seller_id", dependent: :destroy
has_many :purchased, class_name: "Archive", foreign_key: "buyer_id", dependent: :destroy
has_many :sales, class_name: "Archive", foreign_key: "seller_id", dependent: :destroy
has_many :selling_rooms, class_name: "Room", foreign_key: "seller_id", dependent: :destroy
has_many :buying_room, class_name: "Room", foreign_key: "buyer_id", dependent: :destroy
has_many :comments, through: :posts
has_many :posts
has_many :notifications, foreign_key: :recipient_id
def can_buy?(listing_price)
if self.points >= listing_price
true
else
false
end
end
def withdraw(listing_price)
self.points -= listing_price
end
def purchasing_list
purchasing.includes(:seller, :listing)
end
def purchased_list
purchased.includes(:seller, :listing)
end
def sell_list
sell.includes(:seller, :listing)
end
def sales_list
sales.includes(:seller, :listing)
end
end
答案 0 :(得分:1)
我猜你没有以正确的方式宣布这种关系; 你有Post模型吗?:
has_one :user
或者你宣布了
has_many :users
如果是第一个,则会出现当前行为。对于您期望的情况,在您的用户模型(user.rb)
中逻辑上是有意义的has_many :posts
并在你的帖子模型中
belongs_to :user