I have Users which have many Microposts. Microposts belong to a user. Right now only the user can post on his/her profile. How can I allow everyone to post there. I've run a migration that added the column "sender_id" to the Micropost table but I can't seem to figure out how to get this working with the sender_id. I'm new to rails thanks for reading.
Micropost create controller:
@user = User.find(73) #change so it posts to the user page im on
@micropost = @user.microposts.build(params[:micropost])
@micropost.sender_id = current_user.id
if @micropost.save
flash[:success] = "Music Posted!"
redirect_to :back
end
Micropost Form:
<%= form_for(@micropost) do |f| %>
<div class="field">
<%= f.text_area :comment, placeholder: "send a message" %>
</div>
<%= f.submit "Share", class: "btn btn-medium btn-primary" %>
<% end %>
In the Microposts table I want User_id to be the person with the profile and Sender_id to be the user that posts on the other's profile.
Solution was to added hidden_field_tag to the micropost form to get the user_id param set and then @user = User.find(params[:user_id])
You could change your code to this:
@user = User.find(73) #change so it posts to the user page im on
@micropost = @user.microposts.build(params[:micropost])
@micropost.sender = current_user # or whatever indicates your current user
if @micropost.save
flash[:success] = "Music Posted!"
redirect_to :back
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.