3

I would like to add a link into my rails app which will allow my users to "like" a resource (property) directly. To click on that link will add the like into the db without asking anything to the user.

The like table: user_id, property_id

As you can see, user_id and property_id have to be in the link_to as params.

routes.rb:

  resources :likes
  resources :properties

index:

<%= link_to "Like this property", new_like_path(current_user, property.id) %> #does not work but you get the idea

controller:

 def new
    @like = Like.new
  end
def create
    @like = Like.new(like_params)

    respond_to do |format|
      if @like.save
        format.html { redirect_to @like, notice: 'Like was successfully created.' }
        format.json { render action: 'show', status: :created, location: @like }
      else
        format.html { render action: 'new' }
        format.json { render json: @like.errors, status: :unprocessable_entity }
      end
    end
  end

So I am in properties#index and I would like to call a create method to add a like on that property.

2
  • What exactly are you having trouble with? Commented Jun 1, 2014 at 16:18
  • It just does not work. I don't know how to do that kind of link. Commented Jun 1, 2014 at 16:28

1 Answer 1

9

index:-

<%= link_to "Like this property", likes_path(:user_id => current_user.id, :property_id => property.id), :method => :post %>

In controller:-

def create
@like = Like.new(:user_id => params[:user_id], :property_id => params[:property_id])

respond_to do |format|
  if @like.save
    format.html { redirect_to properties_path, notice: 'Like was successfully created.' }
    format.json { render action: 'show', status: :created, location: @like }
  else
    format.html { render action: 'new' }
    format.json { render json: @like.errors, status: :unprocessable_entity }
  end
end
end
Sign up to request clarification or add additional context in comments.

2 Comments

I tried but : # Never trust parameters from the scary internet, only allow the white list through. def like_params params.require(:like).permit(:user_id, :property_id) end It's like the params are not there
yes i have changed. see the link_to in index and Like.new in controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.