【发布时间】:2011-10-07 07:33:47
【问题描述】:
在我的应用中,用户有很多对话,对话有很多消息。我想创建一个新的对话:我必须指定用户(读者)和(第一条)消息。我尝试了以下方法,但失败了。
型号
class Conversation < ActiveRecord::Base
has_many :conversation_users
has_many :users, :through => :conversation_users
has_many :messages
accepts_nested_attributes_for :users
accepts_nested_attributes_for :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
end
class User < ActiveRecord::Base
has_many :conversation_users
has_many :conversations, :through => :conversation_users
end
控制器
def new
@conversation = Conversation.new
2.times do
users = @conversation.users.build
end
messages = @conversation.messages.build
end
def create
@conversation = Conversation.new(params[:conversation])
if @conversation.save
redirect_to username_conversations_path(current_username)
else
redirect_to new_username_conversation_path(current_username)
end
end
查看
<% form_for([current_user, @conversation]) do |f| %>
<% f.fields_for :users do |builder| %>
<%= builder.text_field :id %>
<% end %>
<% f.fields_for :messages do |builder| %>
<%= builder.text_area :content %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
current_user 和 current_username 是 helper 方法,定义如下:
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_username
@current_username ||= current_user.username if current_user
end
这是 Rails 服务器的响应:
Started POST "/users/8/conversations" for 127.0.0.1 at Sun Jul 17 23:58:27 +0200 2011
Processing by ConversationsController#create as HTML
Parameters: {"commit"=>"Submit", "authenticity_token"=>"z6kL+NmVspgCKMr9whcw+a85mA59j3jssS9QeTiEbxc=", "utf8"=>"✓", "conversation"=>{"users_attributes"=>{"0"=>{"id"=>"9"}, "1"=>{"id"=>"10"}}, "messages_attributes"=>{"0"=>{"content"=>"freee"}}}, "user_id"=>"8"}
User Load (0.3ms) SELECT "users".* FROM "users" INNER JOIN "conversation_users" ON "users".id = "conversation_users".user_id WHERE "users"."id" IN (9, 10) AND (("conversation_users".conversation_id = NULL))
ActiveRecord::RecordNotFound (Couldn't find User with ID=9 for Conversation with ID=):
app/controllers/conversations_controller.rb:26:in `new'
app/controllers/conversations_controller.rb:26:in `create'
conversations_controller 第 26 行:@conversation = Conversation.new(params[:conversation])
我怎样才能让它工作?
谢谢。
【问题讨论】:
-
“失败”是什么意思?有什么错误吗?
-
我添加了错误响应...这是一个找不到记录的错误
-
我在您的回复中看不到任何错误
-
什么是
current_username?显示此帮助代码 -
current_username 是当前登录用户的用户名。 current_user 返回当前登录的用户(在这两种情况下,都是正在创建新对话的用户)
标签: ruby-on-rails has-many-through nested-attributes