简体   繁体   中英

Rails 4 - Link_to action create with params

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM