1
我目前有一个简单的应用程序,其中包括通过设计和消息模型进行用户身份验证(消息模型使用Jquery和Faye)。两者都独立工作,但我想添加一个user_id消息。将user_id添加到消息模型
我已经更新了架构和模型的关系,但我有麻烦输入必要的代码让视图和控制器输入到数据库的关系,同时保持jQuery的工作。我不确定最好的方法,但在这里我试图创建一个隐藏的字段,将拉动user_id,不知道这是甚至可能的。这里是适用的代码,任何帮助表示赞赏。
消息index.html.erb
<ul id="chat">
<%= render @messages %>
</ul>
<%= form_for Message.new, :remote => true do |f| %>
<div class="field">
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.hidden_field :user_id %>
</div>
<div class="actions">
<%= f.submit "Send" %>
</div>
<% end %>
create.js.erb的消息
<% broadcast "/messages" do %>
$("#chat").append("<%= escape_javascript render(@user.message) %>");
<% end %>
$("#new_message")[0].reset();
消息控制器
class MessagesController < ApplicationController
def index
if @authentications = current_user
@messages = Message.all
else
redirect_to authentications_url
flash[:notice] = "You need to sign in before answering questions"
end
end
def create
@user = User.find(params[:user_id])
@message = @user.message.create(params[:message])
end
end
我觉得你有你需要的一切,但如果没有,请让我知道,我会很乐意为您提供。
谢谢大家。
谢谢,所以为1)我做它current_user.messages.new,因为他们登录和2)它has_many所以我做了这个改变。现在的问题是,消息没有被提交,我得到一个'ActiveRecord :: RecordNotFound(无法找到没有ID的用户): app/controllers/messages_controller.rb:12:在'创建'错误服务器。 – Igrabes 2011-05-21 04:34:44
这是因为,params [:user_id]没有使用params [:message] [:user_id]。或者你可以尝试使用Message.create(params [:message])创建消息,这应该是有效的,因为消息中有user_id – 2011-05-21 04:39:12
Naren,谢谢你,伙计,你是男人! – Igrabes 2011-05-21 05:01:36