我正在构建一个故事阅读器应用程序,用户可以上传故事并阅读它们。我有story
和profile
模型。我的个人资料show
页面显示了当前用户的个人资料,并显示了他创建的所有故事的标题。但是,点击任何故事标题链接会将我重定向到第一个故事的节目页面,即它会为每个故事选择第一个用户的故事ID。
以下是模型:
class Profile < ActiveRecord::Base
belongs_to :user
end
class Tale < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
belongs_to :category
end
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :tales, dependent: :destroy
end
控制器:
class TalesController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_story, only: [ :show, :edit, :update, :destroy ]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@tales = Tale.all.order("created_at DESC")
end
def new
@tale = current_user.tales.new
end
def create
@tale =current_user.tales.new(tales_params)
if @tale.save
flash[:success] = "Successfully added stories"
redirect_to @tale
else
flash[:error] = "Error in saving"
render action: 'new'
end
end
def show
end
def update
if @tale.update_attributes(tales_params)
flash[:success] = "Story successfully updated"
redirect_to @tale
else
flash[:error] = "Error in updating"
render action: 'edit'
end
end
def destroy
@tale.destroy
redirect_to tales_url
end
def edit
end
private
def tales_params
params.require(:tale).permit(:user_id, :title, :body, :category_id)
end
def set_story
@tale = Tale.find(params[:id])
end
def correct_user
@tale = current_user.tales.find_by(id: params[:id])
redirect_to tales_path, notice: "Not authorized to edit this story" if @tale.nil?
end
end
以及profile/show
<div>
<h2> My Stories </h2>
<ul>
<% current_user.tales.each do |my_story| %>
<li><%= link_to my_story['title'], tale_path(current_user) %></li>
<% end %>
</ul>
</div>
答案 0 :(得分:1)
您正在将current_user
传递给tale_path
而不是my_story
。
尝试更改以下内容:
<div>
<h2> My Stories </h2>
<ul>
<% current_user.tales.each do |my_story| %>
<li><%= link_to my_story['title'], tale_path(current_user) %></li>
<% end %>
</ul>
</div>
以下内容:
<div>
<h2> My Stories </h2>
<ul>
<% current_user.tales.each do |my_story| %>
<li><%= link_to my_story['title'], tale_path(my_story) %></li>
<% end %>
</ul>
</div>