我有这个模型:
class Page < ActiveRecord::Base
attr_accessible :infos, :title
has_many :files
end
class Attachment < ActiveRecord::Base
attr_accessible :desc, :file, :page_id, :title, :file_uid, :file_name
dragonfly_accessor :file
belongs_to :page
end
如何从页面 Controller 获取数据?
我正在尝试这个:
def show
@page = Page.find(params[:id])
#@files = @page.attachment.find_by_name
#@files = Attachment.order(:title)
@files = @page.attachment.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: @page }
end
end
在附件显示 View 中我只是做
<%= @attachment.page.title %>
但是当我尝试从页面 View 或 Controller 中获取值时,我得到了错误:undefined method `attachment'
最佳答案
应该是:
@files = @page.files
并且您必须在Page
中指定关联的类名:
has_many :files, class_name: 'Attachment'
或者你只是在 Page
中使用 has_many :attachments
,然后使用:
@files = @page.attachments
关于ruby-on-rails - Rails 3 - 如何从 has_many 关系中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22864847/