0

ユーザーとガイドラインのモデルがあります。

ユーザーがガイドラインをお気に入りとしてマークしてから、お気に入りのガイドラインすべてのリストを表示できるようにしたいと思います。

それは完全に正しくありません。'favourite'アクションがお気に入りを正しく追加しているかどうかはわかりません。または、正しく追加されている場合は、お気に入りビューに正しく表示されません(したがって、「表示」アクションが正しくない可能性があります)。

*コントローラー*guidelines_controller.rb

def favourite
   type = params[:type]
   if type == "favourite"
    @guideline= Guideline.find_all_by_id(params[:guideline_id])
    current_user.favourite_guidelines << @guideline
     redirect_to :back, notice: 'You favourited #{@guideline.name}'
    elsif type == "unfavourite"
     current_user.favourite_guidelines.delete(@guideline)
     redirect_to :back, notice: 'Unfavourited #{@guideline.name}'

    else
    # Type missing, nothing happens
   redirect_to :back, notice: 'Nothing happened.'
    end
  end

*コントローラー*favourites_controller.rb

 def show

    @user = User.find_by_profile_name(params[:id])
    if @user 
        @guidelines = @user.favourite_guidelines.all
        render action: :show
    else
        render file: 'public/404', status: 404, formats: [:html]
    end
  end
end

*ルート* routes.rb

get "guidelines/favourite"
  get "favourites/show"

*モデル* user.rb

has_many :guidelines
 has_many :favourite_guidelines

*モデル*favourite_guidelines.rb

  attr_accessible :guideline_id, :user_id

  belongs_to :user

*ビュー*guidelines/ index.html.erb

<% if current_user %>
    <%= link_to "favourite",   guidelines_favourite_path(guideline, type: "favourite"), method: "get" %>
    <%= link_to "unfavourite", guidelines_favourite_path(guideline, type: "unfavourite"), method: "get" %>

*ビュー*favourites/ show.html.erb

<% if @guidelines %>
    <% @guidelines.each do |guideline| %>

        <div class="well">
            <%= link_to guideline.title, guideline %>
            <br />
            <%= guideline.content %>
            <br />
            Added <%=  time_ago_in_words(guideline.created_at) %> ago
        </div>
    <% end %>
<% end %>
4

1 に答える 1

1

あなたのコメントに従って、次のリターンが返されますnil

@guideline= Guideline.find_by_id(params[:guideline_id])  #=> nil
current_user.favourite_guidelines << nil #Gives association mismatch error 

だと思いparams[:guideline_id]ますnil。ログファイルからパラメータを投稿してください。

またはこれを試してください:

リンクを次のように変更します。

<%= link_to "favourite",   guidelines_favourite_path(guideline_id: guideline.id, type: "favourite"), method: "get" %>
<%= link_to "unfavourite", guidelines_favourite_path(guideline_id: guideline.id, type: "unfavourite"), method: "get" %>

以前のケースでは:

 @guideline= Guideline.find_all_by_id(params[:guideline_id]) #=> []
 current_user.favourite_guidelines << [] #=> Valid and inserting nothing
于 2013-02-16T12:40:11.163 に答える