在link_to中设置控制器操作

时间:2014-08-21 18:50:48

标签: ruby-on-rails

我需要帮助,允许用户点击“关注/取消关注”链接,并在用户显示页面上执行操作。目前我在弹出窗口中有动作,我不知道如何在链接动作中设置它,所以不需要弹出窗口。

我尝试在显示页面上渲染表单,但这并没有像我预期的那样显示。

show.html.slim:

        - if current_user.following?(@user)
      = link_to follow_popup_user_path(@user), class: 'profile_btn save_btn', :'data-mfp-src'=>'#follow_div', remote: true do
        = image_tag 'start_icon.png'
        span Unfollow
      - else
        = link_to follow_popup_user_path(@user), class: 'profile_btn save_btn', :'data-mfp-src'=>'#follow_div', remote: true do
          = image_tag 'start_icon.png'

_follow.html.slim:

= form_for(current_user.relationships.build(followed_id: @user.id)) do |f|
  div
    = f.hidden_field :followed_id
    = f.submit "Follow", class: "btn btn-large btn-primary"

_unfollow.html.slim:

= form_for(current_user.relationships.find_by(followed_id: @user),
             html: { method: :delete }) do |f|
  = f.submit "Unfollow", class: "btn btn-large"

关系控制器:

  def create
    @user = User.find(params[:relationship] [:followed_id] )
    current_user.follow!(@user)
    redirect_to @user
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
    redirect_to @user
  end
end

1 个答案:

答案 0 :(得分:0)

您不应该需要一个表单,只需将正确的参数传递给嵌套的关系路径,然后处理user模型followunfollow中的细节方法。尝试这样的事情:

的用户/ show.slim

- if current_user.following?(@user)
  = link_to new_user_relationship_path(id: current_user.id, followed_id: @user.id), class: 'profile_btn save_btn' do
    = image_tag 'start_icon.png'
    span Unfollow
- else
  = link_to user_relationship_path(id: current_user.id, followed_id: @user.id), method: delete, class: 'profile_btn save_btn' do
    = image_tag 'start_icon.png'

路由

resources :users do
  resources :relationships

relationships_controller

def create
  @user = User.find(user_params(:id))
  @followed_user = User.find(user_params(:followed_id))
  @user.follow @followed_user
  redirect_to @user
end

def destroy
  @user = User.find(user_params(:id))
  @followed_user = User.find(user_params(:followed_id))
  @user.unfollow @followed_user
  redirect_to @user
end

private
  def user_params
    params.require(:user).permit(:followed_id, )
  end