How to prepopulate form with data passed from @object?

后端 未结 2 1462
天命终不由人
天命终不由人 2021-01-23 06:38

On my website a user can upload \"inspirations\" aka images or text that a user finds inspirational.

I want to create a feature, like Pinterest, where a user ca

2条回答
  •  长情又很酷
    2021-01-23 07:17

    Why are you duplicating functionality?

    If someone "pins" an inspiration, is it not the case that the inspiration will be the same one the other user uploaded? Which means, you should have functionality to create a pin, not an inspiration.


    I'll delete this if out of context, but here's what I'd do:

    #config/routes.rb
    resources :inspirations do
       match :pin, via: [:post, :delete], on: :member #-> url.com/inspirations/:id/pin
    end
    
    #app/controllers/inspirations_controller.rb
    class InspirationsController < ApplicationController
       def pin
          @inspiration = Inspiration.find params[:id]
          if request.post?
             current_user.pins << @inspiration
          elsif request.delete?
             current_user.pins.delete @inspiration
          end
       end
    end
    

    This will allow you to use:

    #app/views/inspirations/index.html.erb
    <% @inspirations.each do |inspiration| %>
       <%= link_to "Pin", inspiration_pin_path(inspiration) %>
    <% end %>
    

    --

    If you wanted to add extra attributes for the "pin" (such as a custom caption etc), you'll be able to do it with a simple form...

    #app/views/inspirations/index.html.erb
    <% @inspirations.each do |inspiration| %>
       <%= form_for inspiration, url: inspiration_pin_path(inspiration) do |f| %>
          <%= f.text_field :caption %>
          <%= f.submit %>
       <% end %>
    <% end %>
    

提交回复
热议问题