【发布时间】:2015-11-30 21:39:47
【问题描述】:
我有两种用户类型:艺术家和粉丝。我希望粉丝能够关注艺术家。到目前为止,跟随它们不起作用,但不跟随却可以。我有 create 和 destroy 设置相同的方式,但似乎无法让它工作。尝试create 关系时,我收到错误找不到没有 ID 的艺术家。无论如何我可以找到艺术家的 ID?
代码如下:
relationships_controller.rb
class RelationshipsController < ApplicationController
before_action :authenticate_fan!
def create
@relationship = Relationship.new
@relationship.fan_id = current_fan.id
@relationship.artist_id = Artist.find(params[:id]).id #the error
if @relationship.save
redirect_to (:back)
else
redirect_to root_url
end
end
def destroy
current_fan.unfollow(Artist.find(params[:id]))
redirect_to (:back)
end
end
artists_controller.rb
def show
@artist = Artist.find(params[:id])
end
艺术家/show.html.erb
<% if fan_signed_in? && current_fan.following?(@artist) %>
<%= button_to "unfollow", relationship_path, method: :delete, class: "submit-button" %>
<% elsif fan_signed_in? %>
<%= form_for(Relationship.new, url: relationships_path) do |f| %>
<%= f.submit "follow", class: "submit-button" %>
<% end %>
<% end %>
models/fan.rb
has_many :relationships, dependent: :destroy
has_many :artists, through: :relationships
belongs_to :artist
def following?(artist)
Relationship.exists? fan_id: id, artist_id: artist.id
end
def unfollow(artist)
Relationship.find_by(fan_id: id, artist_id: artist.id).destroy
end
models/artists.rb
has_many :relationships, dependent: :destroy
has_many :fans, through: :relationships
belongs_to :fan
routes.rb
resources :relationships, only: [:create, :destroy]
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4