我无法找到无法将记录保存到数据库中的原因...帮助我找到我在模型和控制器中出错的原因。
has_many :interested_users_lists
has_many :interested_posts, through: :interested_users_lists
accepts_nested_attributes_for :interested_users_lists, :interested_posts
...等
class InterestedUsersList < ApplicationRecord
# belongs_to :post
# belongs_to :users
belongs_to :interested_post, class_name: 'Post'
belongs_to :interested_user, class_name: 'User'
end
belongs_to :owner, :class_name => "User", :foreign_key => "user_id", touch: true
has_many :interested_users_lists, dependent: :destroy
has_many :interested_users, through: :interested_users_lists
accepts_nested_attributes_for :interested_users_lists, :interested_users
...等 我使用的方法:
# add interested user
def add_interested_user(user)
puts "this is user id: #{user.id} "
interestedUser = self.interested_users_lists.build(user_id: user.id)
interestedUser.save
puts "this is #{interested_users_lists.first.user_id} "
end
class CreateInterestedUsersLists < ActiveRecord::Migration[5.0]
def change
create_table :interested_users_lists do |t|
t.integer :user_id
t.integer :post_id
t.timestamps
end
end
end
def interested
@post.add_interested_user(current_user) #cannot be saved...
end
...
private
def post_params
params.require(:post).permit(:subject, :price, :category, :street_address, :city, :state, :zip, :condition, :payment_method, :content, post_attachments_attributes: [:id, :post_id, :avatar],
interested_users_lists_attributes: [:id, :post_id, :user_id])
end
开发日志
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? ORDER BY "posts"."created_at" DESC LIMIT ? [["id", 1], ["LIMIT", 1]]
this is user id: 2
**(0.0ms) begin transaction
(0.1ms) rollback transaction** _why???_
InterestedUsersList Load (0.1ms) SELECT "interested_users_lists".* FROM "interested_users_lists" WHERE "interested_users_lists"."post_id" = ? [["post_id", 1]]
this is 2
Redirected to http://localhost:3000/users/posts/2
Completed 302 Found in 77ms (ActiveRecord: 4.9ms)
Started GET "/users/posts/2" for ::1 at 2016-12-27 03:04:33 -0800
答案 0 :(得分:0)
更改此方法您不需要保存直通记录
# add interested user
def add_interested_user(user)
self.interested_users << user
end