Sasha
Sasha

Reputation: 3281

rails, how to retrieve an :id attribute in controller

im trying to create a simple private messaging system

i have a nested route

resources :users do
   resources :messages
end

on my users show page, i have...

    <%= form_for([current_user, @message])  do |f| %>
      <div class="field">
        <%= f.text_area :content, placeholder: "Send a private message..." %>
      </div>
      <%= f.submit "Post", class: "btn btn-large btn-primary" %>
    <% end %>

where the current user can send a private message to the user currently being looked at.

on my message.rb i have...

belongs_to :user

and in user.rb i have...

has_many :messages

on my user controllers show action i have

def show
 @user = User.find(params[:id])
 @microposts = @user.microposts.paginate(page: params[:page])
 if user_signed_in?
    @message = current_user.messages.build(params[:messages])
 end

end

when a user hits the submit button on my show template, it goes to my messages create action, however im unable to get the id of the user i was looking at (or trying to send to)

i printed out my message variable, and it says...

[#<Message id: nil, content: nil, user_id: 1, to_id: nil, created_at: nil, updated_at: nil>]

the :user_id is the current user (which is me, with an id of 1), however i can't seem to get the to_id (which was the user i was just looking at, lets say his id was 2)

can someone please tell me how i can retrieve it? i can only think of passing the id as a hidden field, but i heard that's not safe to do.

help would be greatly appreciated. thanks

update: @Andrew

hmm actually its interesting because if i do...

@message = current_user.messages.build(to_id: @user.id)

and i pass in

<%= f.hidden_field :to_id, :value => @user.id %>

i get a

Can't mass-assign protected attributes: to_id. 

does anyone know why?

Upvotes: 0

Views: 1720

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10099

On your show page, put in a hidden field.

<%= form_for([current_user, @message])  do |form| %>
  <%= form.hidden_field :to_id, :value => @user.id %>

Upvotes: 1

Andrew
Andrew

Reputation: 43153

There's nothing wrong with putting a UserID in a hidden field, it's visible in the URL to begin with.

If you add the to_id in your show action and have a hidden field on that in your form it will flow from the users#show action into the message form and then to the messages#create action when that form is posted.

def show
 @user = User.find(params[:id])
 @microposts = @user.microposts.paginate(page: params[:page])
 if user_signed_in?
    @message = current_user.messages.build(to_id: @user.id)
 end

end

Note that the show action is not receiving any params[:messages], because you do not post to this. Unless your URL looks like this: users/1?messages=foo then that params value will always be nil.

Upvotes: 1

Related Questions