开发者

Adding a user_id to a Message model

开发者 https://www.devze.com 2023-03-07 04:49 出处:网络
I currently have a simple app that includes user authentication through devise and a message model(the message model uses Jquery and Faye). Both are working fine independently, but I would like to add

I currently have a simple app that includes user authentication through devise and a message model(the message model uses Jquery and Faye). Both are working fine independently, but I would like to add a user_id to the messages.

I have already updated the schema and models with the relationship, but I am having trouble inputting the necessary code to have the view and controller input the relationship into the db, while keeping the jquery working. I wasn't sure of the best way, but here I tried to create a hidden field that would pull the user_id, not sure if this is even possible. Here is the applicable code, any help is appreciated.

Message 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 for messages

 <% broadcast "/messages" do %>
 $("#chat").append("<%= escape_javascript render(@user.message) %>");
 <% end %>
 $("#new_message")[0].reset();

Messages Controller

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[开发者_如何学C:user_id])
  @message = @user.message.create(params[:message])
 end
end

I think you have everything you would need, but if not, let me know and I will be happy to provide it for you.

Thanks, everyone.


two things to correct,

1)use user association to create message instance in form(probably current_user if logged-in user create a message)

<%= form_for user.messages.new, :remote => true do |f| %> #// assuming its has many association

2) if it is has_many association then change association in create action

@message = @user.messages.create(params[:message])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号