Guest User

Untitled

a guest
Jun 24th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #trying to be able to get the message author in the view easily.
  2.  
  3. class Message < ActiveRecord::Base
  4. has_many :msg_owners
  5. has_many :users, :through => :msg_owners
  6. has_one :author, :source => :user, :through => :msg_owners, :conditions => ["users.author = ?",true]
  7. end
  8.  
  9. class User < ActiveRecord::Base
  10. has_many :msg_owners
  11. has_many :messages, :through => :msg_owners
  12. end
  13.  
  14. #this table has a record for everyone who can see the message. The boolean author field is true for the person that originated the message
  15. class MsgOwners < ActiveRecord::Base
  16. belongs_to :user
  17. belongs_to :message
  18. end
  19.  
  20. index controller
  21. def create
  22. @message = Message.new(params[:message])
  23. respond_to do |format|
  24. if @message.save
  25. #add a record in the MsgOwners table that designates the author. Any recipients would also get a record but boolean would be false.
  26. @msg_owner = MsgOwners.new(:user_id => current_user.id, :message_id => @message.id, :author => true)
  27. @msg_owner.save
  28. flash[:notice] = 'Message was successfully created.'
  29. @messages = Message.find(:all, :order => "created_at DESC")
  30. format.html { render :action => "index" }
  31. format.xml { render :xml => @message, :status => :created, :location => @message }
  32. else
  33. format.html { render :action => "new" }
  34. format.xml { render :xml => @message.errors, :status => :unprocessable_entity }
  35. end
  36. end
  37. end
  38.  
  39. index view
  40. <% @messages.each do |message| %>
  41. <%=h trying to get author's name here %> said "<%=h message.message %>"<br/>
  42. <%=h message.time_ago_or_time_stamp %>
  43. <% end %>
Add Comment
Please, Sign In to add comment