i have this form_for sending a private message between two users on my users#show template
<%= form_for([current_user, @message]) do |f| %>
<%= f.hidden_field :to_id, :value => @user.id %>
<div class="message_field">
<%= f.text_area :content, placeholder: "Send a private message..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<span class="message_countdown"></span>
<% end %>
and in my message model, i have
belongs_to :to,
:class_name => 'User',
:foreign_key => :to_id
validates :content, presence: true, length: { maximum: 1000 }
validates :user_id, :to_id, presence: true
what is weird is that the very first time a user gets created and they navigate to their show profile,
they already get this error
The form contains 2 errors.
* Content can't be blank
* To can't be blank
once i refresh the page, they disappear. and the form functions normally. i can’t seem to figure out what is wrong. does the form already try to auto submit by itself?
on my messages#create action i have
def create
@message = current_user.messages.build
@message.to_id = params[:message][:to_id]
@message.user_id = current_user.id
@message.content = params[:message][:content]
if @message.save
flash[:success ] = "Private Message Sent"
end
redirect_to user_path(params[:message][:to_id])
end
if that sheds any light. im manually assigning the @msessage attributes because i didn’t want to make :user_id attr_accessible.
but still, why does the validation already fail just by going to the page the very first time? im not submitting. once i leave the page and come back to it, the error doesn’t occur anymore.
here is my users#show action
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
@current_user = current_user
if user_signed_in?
@message = current_user.messages.build(params[:messages], to_id: @user.id)
end
@influence = current_user.points
@badge_items = current_user.badges.to_a.map(&:name)
end
does it have to do something with my show action? specifically
@message = current_user.messages.build(params[:messages], to_id: @user.id)
is that calling a create?
help would be appreciated. thank you!
UPDATE. i fixed it!
instead of…
@message = current_user.messages.build(params[:messages], to_id: @user.id)
i just did
@message = current_user.messages.build
i guess the issue was more of…it was looking for the messages value and the user id, which there isnt any yet passed. thank you!
Yes,
is attempting to create a
Messageobject.Here’s a link to the Rails guide on
has_manythat describes the specifics of howmessages.buildwill be building a new record.http://guides.rubyonrails.org/association_basics.html#has_many-association-reference