Passing an instance variable into a form - rails

元气小坏坏 提交于 2019-12-05 20:47:18
tmaximini

You can do something like this:

<% form_for Like.new, :remote => true do |f| %>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.submit %>
<% end %>

The current_user.likes.build(...) part should get out of your view and inside your controller. You are using a current_user.like! method so I guess you have implemented already some method in user model to accomplish this. If not build your like in the create action of LikesController where you can access params[:like].

  def create
    @post = Post.find(params[:like][:post_id])
    current_user.likes.build(@post)
    # ...
  end

EDiT

You might need to pass your @post variable correctly into your _like_form partials, like so:

#views/posts/_post.html.erb:
...
<% if signed_in? %>
  <%= render 'posts/like_form', :post => @post %>
<% end %>
...

This will give you acceess to a post variable inside the partial so you can prepopulate your forms value with its id. See this questions as well Pass a variable into a partial, rails 3? and make sure to read up on how to pass variables correctly to partials. you can debug your views using <%= debug <variablename> %>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!