2

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 can click on a image or text to "pin it" instead of having to upload his own.

enter image description here

Upon clicking the button I want the user to be redirected to inspirations/_form with the appropriate fields populated.

enter image description here

For example, I tried passing it in the path with new_inspiration_path({image: inspiration.image}), but that didn't have an effect.

<% @inspirations.each do |inspiration| %>
  <%= link_to new_inspiration_path, data: { modal: true } do %>
  <span class="glyphicon glyphicon-plus"></span>
  <% end %>
  <%= link_to image_tag(inspiration.image.url(:medium)), inspiration %>
<% end %>
AnthonyGalli.com
  • 2,796
  • 5
  • 31
  • 80

2 Answers2

3

You should assign this object in your controller action, something like this:

def new
  @inspiration = Inspiration.find(params[:inspiration_id])
end

And the path should be:

new_inspiration_path(inspiration_id: inspiration.id)
Oleg
  • 214
  • 1
  • 2
  • The problem may be in your controller create action or something in your form view code. – Oleg Jan 10 '16 at 08:53
  • Seems you need something like this `if params[:inspiration_id] @inspiration = Inspiration.find(params[:inspiration_id]) else @inspiration = current_user.inspirations.build end` Sorry for code formatting. – Oleg Jan 11 '16 at 02:17
1

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 %>
Richard Peck
  • 76,116
  • 9
  • 93
  • 147