Rails 4 - Link_to动作用params创建

时间:2014-06-01 16:13:59

标签: ruby-on-rails link-to

我想在我的rails应用程序中添加一个链接,这将允许我的用户"喜欢"资源(属性)直接。单击该链接会将相同内容添加到数据库中,而不向用户询问任何内容。

like表:user_idproperty_id

如您所见,user_idproperty_id必须在link_to中作为参数。

routes.rb中:

  resources :likes
  resources :properties

指数:

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

控制器:

 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

所以我在properties#index,我想调用create方法在该属性上添加类似内容。

1 个答案:

答案 0 :(得分:6)

索引: -

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

在控制器中: -

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