【发布时间】:2014-03-13 06:36:42
【问题描述】:
我有一个用户对用户的消息传递系统。我正在尝试将一组用户 ID 传递给 ConversationUser(连接表)模型,然后该模型将从每个 user.id 中创建多个 conversation_users。 ConversationUser 中的两个字段是 conversation_id 和 user_id。我能够初始化单个对话用户,因为新的 conversation_id 正在传递给模型,但由于某种原因,用户 ID 的哈希没有进入我的模型。我收到了Validation failed: User can't be blank
我的对话/捕获 user_ids 的新视图:
<%= check_box_tag "conversation_user[recipient][]", user.id %> <%= user.name %><br />
我知道这是有效的,因为我收到的部分参数是:
"conversation_user"=>{"recipient"=>["9", "10"]}
我的 Rails 4 控制器和强大参数的要点:
class ConversationsController < ApplicationController
def new
@user = User.find(params[:user_id])
@conversation = @user.conversation_users.build
@conversation.build_conversation.messages.build
end
def create
@conv = Conversation.create!
@conversation = @conv.conversation_users.create!(conversation_user_params)
end
def conversation_user_params
params.require(:conversation_user).permit(recipient: [])
end
我的 ConversationUser 模型的要点:
class ConversationUser < ActiveRecord::Base
attr_accessor :recipient
before_create :acquire_conversation
validates :user_id, :conversation_id, presence: true
def acquire_conversation
unless recipient.blank?
recipient.each do |u|
ConversationUser.create(user_id: u, conversation: conversation)
end
end
end
end
我认为问题出在我控制器的conversation_user_params 中。但它也可能在模型的before_create 方法中。我已经尝试解决这个问题一天了,进行了大量调试但没有成功。如果有人可以提供帮助,我提前感谢您。
【问题讨论】:
标签: ruby-on-rails ruby activerecord strong-parameters actioncontroller