【发布时间】:2011-07-04 00:03:18
【问题描述】:
我正在制作一个屏幕,人们通过将图片从画廊拖到托盘中来“投票”给彼此最喜欢的图片。我将 jQuery 用于可拖动/可放置。当用户将图像从图库拖到托盘时,我想更新我的 has_many :through 数据库中的关系(假期投票)。我正在尝试使用 hidden_field_tag 进行投票。
表单提交时我没有得到传递的参数。任何人都知道如何做到这一点?提前致谢!
模型
假期
class Vacation < ActiveRecord::Base
belongs_to :user
belongs_to :period
has_many :votes
has_many :images, :through => :votes
accepts_nested_attributes_for :votes
attr_accessible :user_id, :period_id, :name
end
投票
class Vote < ActiveRecord::Base
belongs_to :vacation
belongs_to :image
attr_accessible :image_id, :vacation_id
end
图片
class Image < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :votes
has_many :vacations, :through => :votes
attr_accessible :user_id, :title, :facebook_id, :image
validates_presence_of :user_id;
validates_presence_of :title;
validates_presence_of :image;
validates_length_of :title, :maximum => 255
mount_uploader :image, ImageUploader
end
Javascript
var $gallery = $( "#gallery" ),
$tray = $( "#tray_images" );
$( "li", $gallery ).draggable({
cancel: "a.ui-icon",
revert: "invalid",
cursor: "move",
helper: "clone"
});
$tray.droppable({
accept: "#gallery > li",
drop: function( event, ui ) {
moveImageToTray( ui.draggable );
$( "#update_vacation" ).submit();
}
});
function moveImageToTray( $item ) {
$item.fadeOut(function() {
$tray.append($item);
$item.fadeIn();
});
}
视图 /vacations/show.html.erb
<%= form_for @vacation, :html => { :method => :put, :id => "update_vacation" } do |f| %>
<%= hidden_field_tag :user_id, @vacation.user_id %>
<%= hidden_field_tag :period_id, @vacation.period_id %>
<%= hidden_field_tag :name, @vacation.name %>
<div id="tray" class="grid_19 push_1 alpha">
<ul id="tray_images" class="gallery">
<% @votes.each do |vote| %>
<li class="grid_3 image">
<% link_to @images_all[i] do %>
<% content_tag :div do %>
<%= image_tag @images_all[i].image_url(:thumb_100_100) %>
<%= hidden_field_tag "vacation[][image_ids]", vote.image_id %>
<% end %>
<% end %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="clear"></div>
<div class="grid_24">
<ul id="gallery" class="grid_19 push_1 alpha gallery">
<% @images_all.each do |image| %>
<li class="grid_3 image">
<% link_to image do %>
<% content_tag :div do %>
<%= image_tag image.image_url(:thumb_100_100) %>
<%= hidden_field_tag "vacation[image_ids][]", image.id %>
<% end %>
<% end %>
</li>
<% end %>
<% end %>
</ul>
控制器
def update
params[:vacation][:votes] ||= []
break
@vacation = Vacation.find(params[:id])
if @vacation.update_attributes(params[:vacation])
redirect_to @vacation, :notice => "Successfully updated vacation."
else
render :action => 'edit'
end
end
【问题讨论】:
标签: jquery ruby-on-rails draggable has-and-belongs-to-many