如何从另一个视图链接到我的附件

时间:2014-05-12 09:32:30

标签: ruby-on-rails

视图/ homework.html.erb

 <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.

视图/ static_pages / home.html.erb

   <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>

控制器/ static_pages_controller.rb

class StaticPagesController < ApplicationController
    def home
      if signed_in?
        @homework = current_user.homeworks.build 
        @feed_items = current_user.feed.paginate(page: params[:page])
      end
    end

控制器/ homeworks_controller.rb

   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

2 个答案:

答案 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?%>

或者您遍历所有作业并链接到列表中的每个附件。