我正在开展一个展示不同画廊内容的项目.基本思想是当用户看到画廊的名称(名称是链接)时能够点击所选择的名称.然后显示属于此库的所有图像.在底部应该有一个链接“在此库中添加图像”.
我的模特:
class gallery < ActiveRecord::Baseattr_accessible :namehas_many :pictures endclass Picture < ActiveRecord::Base attr_accessible :image belongs_to :gallery end
我在gallery_ID上为’pictures’表创建了索引.
我的大问题出现在这里,如何将gallery_ID传递给控制器的动作’new’.正如我在“使用Rails进行敏捷Web开发”中看到的那样,它可能是:
<%= link_to'在此处添加图片...',new_picture_path(:gallery_ID => @ gallery.ID)%>
在这种情况下似乎是foreign_key:gallery_ID在浏览器的URL栏中公开.第二个问题是:gallery_ID可用于控制器的“新”功能,但“创建”功能“消失”(导致错误“无法找到没有ID的图库”).
当我在图片的_form中添加隐藏字段时,问题就消失了,在我的情况下:
<%= form_for(@picture) do |f| %><div > <%= f.hIDden_fIEld :gallery_ID,:value=>params[:gallery_ID] %><%= f.label :image %><br /><%= f.file_fIEld :image %></div><div ><%= f.submit "Create" %></div><% end %>
以下是我在’pictures’控制器中的定义:
def new@gallery=gallery.find(params[:gallery_ID])@picture=@gallery.pictures.build enddef create @gallery = gallery.find(params[:gallery_ID]) @picture = @gallery.pictures.new(params[:picture]) if @picture.save redirect_to(@picture,:notice => 'Picture was successfully created.') else redirect_to(gallerIEs,:notice => 'Picture was NOT created.') end end
最后,show.HTML.erb中的link_to定义为画廊:
<% for picture in selpics(@gallery) %> <div ID= "thumb" > <%= image_tag picture.image %> </div><% end %> <%= link_to 'Add a picture here...',new_picture_path(:gallery_ID=>@gallery.ID) %>
这是提交图像之前的调试输出:
—!map:ActiveSupport :: HashWithindifferentAccess
gallery_ID:“6”
行动:新的
控制器:图片
并在提交“创建”按钮后(提出异常):
{"utf8"=>"✓","authenticity_token"=>"IGI4MfDgbavBShO7R2PXIiK8fGjkgHDPbI117tcfxmc=","picture"=>{"image"=>"wilsonblx.png"},"commit"=>"Create"}
如你所见,“pictures”哈希中没有“gallery_ID”.
向您总结我的问题:
>有没有办法在没有hIDden_fIEld的情况下传递foreign_key?
>我能以某种方式隐藏传递URL栏中显示的外键表单吗?
>使用’link_to’传递参数是否有替代方法?
谢谢 .
解决方法 您可能需要考虑在嵌套资源上阅读Rails指南:http://guides.rubyonrails.org/routing.html#nested-resources
简而言之:
的routes.rb
resources :gallerIEs do resources :pictures doend# Generates the routes: /gallerIEs/:gallery_ID/pictures
pictures_controller.rb
def new @gallery = gallery.find(params[:gallery_ID]) @picture = Picture.newenddef create @gallery = gallery.find(params[:gallery_ID]) # gallery_ID is passed in the URL @picture = @gallery.build(params[:picture]) if @picture.save # success else # fail endend
图片/ new.HTML.erb
<%= form_for [@gallery,@picture] do |f| %> <div > <%= f.hIDden_fIEld :gallery_ID,:value=>params[:gallery_ID] %> <%= f.label :image %><br /> <%= f.file_fIEld :image %> </div> <div > <%= f.submit "Create" %> </div><% end %>
好的,所以gallery_ID仍然通过URL传递,但我真的没有看到任何错误.你必须把它传递到某个地方,对吧?你真正只有3个理智的选择:传递它的位置:隐藏字段,查询字符串参数,或者隐藏在URL(嵌套资源)中.在3中,后者是恕我直言最干净的方法.
如果你想让事情变得更加轻松,我强烈建议您查看Jose Valim的继承资源宝石,它会为您解决许多样板问题:
https://github.com/josevalim/inherited_resources
总结以上是内存溢出为你收集整理的ruby-on-rails – 将foreign_key值传递给Rails控制器的更好方法全部内容,希望文章能够帮你解决ruby-on-rails – 将foreign_key值传递给Rails控制器的更好方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)