<span class="content">
<%= homework.content %></span>
<span class="timestamp">
#this link I want to put it to home page
<%=link_to "attachment", homework.attachment_url if homework.attachment?%>
Posted <%= time_ago_in_words(homework.created_at) %> ago.
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content">
<%= feed_item.content %>
</span>
<span class="timestamp">
<--Here I want put a link "attachment" from view/homework.html.erb -->
Posted <%= time_ago_in_words(homework.created_at) %> ago.
</span>
class StaticPagesController < ApplicationController
def home
if signed_in?
@homework = current_user.homeworks.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
@homework = current_user.homeworks.build(homework_params)
if @homework.save
flash[:success] = "Homework created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@homework.destroy
redirect_to root_url
end
def index
@homeworks=Homework.all
end
private
def homework_params
params.require(:homework).permit(:content,:attachment)
end
def correct_user
@homework = current_user.homeworks.find_by(id: params[:id])
redirect_to root_url if @homework.nil?
end
end
如何在控制器中定义该方法? 我只是运行所有
的迁移AddAttachmentToHomeworks答案 0 :(得分:0)
<--Here I want put a link "attachment" from view/homework.html.erb -->
你以错误的方式思考它
Rails建立在MVC programming pattern之上,意味着每个view
都是自治的 - 这意味着它不会拥有自己的任何数据;它必须继承controllers
<强>控制器强>
从另一个视图中包含attachment
的问题,从控制器开始。
当您呈现view/static_pages/home.html.erb
时,您实际上在home
控制器中呈现static_pages
操作
这意味着当您在其他视图中呈现homework
附件时,需要在home
控制器操作中调用相同的数据,如下所示:
#app/controllers/static_pages.rb
class StaticPagesController < ApplicationController
def home
homework = Homework.find "4"
end
end
答案 1 :(得分:0)
了解您从应用程序中提供的内容,我怀疑用户有多个相关的家庭作业项目。所以你能做的就是
<%=link_to "attachment", feed_item.user.homeworks.last.attachment_url if !feed_item.user.homeworks.last.nil? && feed_item.user.homeworks.last.attachment?%>
或者您遍历所有作业并链接到列表中的每个附件。