我有has_many:通过关系的3个模型。用户,活动和图库。在方法new
和create
在gallery_controller
我需要得到event_id,但是我得到一个零的event_id。但在Mozilla控制台和参数中,存在该id。我不是我做错了什么?ID无零has_many:通过但在参数存在:ID
我也想知道new
和create
动作的结构是否正常?我想在创建之前添加一个活动画廊,并且在current_user画廊中同时添加一个活动画廊,但我无法通过之前的问题对其进行测试。
谢谢和欢呼。
class Event < ActiveRecord::Base
has_many: galleries
has_many: users, through: : galleries, : source => : users, : dependent => : destroy
accepts_nested_attributes_for: users
accepts_nested_attributes_for: galleries
end
class User < ActiveRecord::Base
has_many :galleries
has_many :events, through: :galleries, :dependent => :destroy
accepts_nested_attributes_for :events
accepts_nested_attributes_for :galleriesenter code here
end
class Gallery < ActiveRecord::Base
has_many :pictures, :dependent => :destroy
belongs_to :event
belongs_to :user
end
Gallery_controller
def new
@event = Event.find(params[:event_id])
@galery = Gallery.new
respond_to do |format |
format.html# new.html.erb
format.json {
render json: @gallery
}
end
end
def create
@event = Event.find(params[:id])
@gallery = @event.galleries.build(params[:gallery])
@gallery.user = current_user
respond_to do |format |
[email protected] gallery.save
if params[: images]# The magic is here;)
params[: images].each { | image | @gallery.pictures.create(image: image)
}
end
def gallery_params
params.require(:gallery).permit(:description,
:name,
:pictures,
:event_attributes => [],
:user_attributes => [],
)
end
form_新画廊
<%= form_for [@event,@gallery], :html => { :class => 'form-horizontal', multipart: true } do |f| %>
<div class="control-group">
<%= f.label :name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :name, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :description, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :description, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :pictures, :class => 'control-label' %>
<div class="controls">
<%= file_field_tag "images[]", type: :file, multiple: true %>
</div>
</div>
<div class="form-actions">
<%= f.submit :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
galleries_path, :class => 'btn btn-mini' %>
</div>
<% end %>
路线
resources :events do
resources :galleries
end
图片错误
http://i.stack.imgur.com/mk1Ti.png
谢谢! <%= f.hidden_field:event_id%>起作用! –