Ale*_*eil 1 ruby-on-rails ruby-on-rails-4
我有两种用户类型:艺术家和粉丝.我希望粉丝能够跟随艺术家.到目前为止,它们不起作用,但取消后续工作.我有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
Run Code Online (Sandbox Code Playgroud)
artists_controller.rb
def show
@artist = Artist.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)
艺术家/ 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 %>
Run Code Online (Sandbox Code Playgroud)
车型/ 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
Run Code Online (Sandbox Code Playgroud)
车型/ artists.rb
has_many :relationships, dependent: :destroy
has_many :fans, through: :relationships
belongs_to :fan
Run Code Online (Sandbox Code Playgroud)
的routes.rb
resources :relationships, only: [:create, :destroy]
Run Code Online (Sandbox Code Playgroud)
基本上,您需要发送artist_id到操作.改变你form的想法.需要进行大量的重构,但这一步对您有用:
<%= form_for(Relationship.new, url: relationships_path) do |f| %>
<%= hidden_field_tag :artist_id, @artist.id %>
<%= f.submit "follow", class: "submit-button" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
在控制器中,您可以像以下一样访问它:
@relationship.artist_id = Artist.find(params[:artist_id]).id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
556 次 |
| 最近记录: |