我有一个用户到用户的消息传递系统。我试图将一组用户ID传递给ConversationUser
(连接表)模型,然后从每个user.id
创建多个conversation_users
。 ConversationUser
中的两个字段分别为conversation_id
和user_id
。我可以初始化一个对话用户,因为新的conversation_id
被传递给模型,但由于某种原因,用户id的散列没有进入我的模型。我得到一个Validation failed: User can't be blank
Rails:将参数哈希值传递给模型
我谈话/新视图用于捕捉user_ids:
<%= check_box_tag "conversation_user[recipient][]", user.id %> <%= user.name %><br />
我知道这是工作,因为我的PARAMS是我收到回的部分是:
"conversation_user"=>{"recipient"=>["9", "10"]}
我的Rails的要点4控制器&强PARAMS:
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
方法中。我一直试图解决这个问题一天,大量的调试没有成功。如果任何人能够提供帮助,我提前感谢你。
我看到我的错误。非常感谢你。这工作很好。 – user3181113