我正在使用 rails 3.2.14 并且第一次使用 has_many :through 时遇到问题。我正在使用 has_many :through 使用 Design_Pictures 表的 Image 和 Design 表之间的关系,该表将存储设计图像的顺序排名。所有图像都与一个用户相关联。稍后我希望能够灵活地将其他图像存储在与特定设计无关的图像表中。
我可以成功地将示例数据添加到我的数据库中,并在我的展示设计页面中显示图像标题(存储在 images 表中)和排名(存储在 design_pictures 表中)。我想不通的是如何创建一个新的design_picture。一旦我可以完成这项工作,我将使用 CarrierWave 或 Paperclip 将图像添加到图像表中。
这是我的模型:
应用程序/模型/image.rb:
class Image < ActiveRecord::Base
attr_accessible :title
belongs_to :user
has_many :design_pictures, dependent: :destroy
has_many :designs, :through => :design_pictures
validates :user_id, presence: true
validates :title, length: { maximum: 80 }
end
应用程序/模型/设计.rb:
class Design < ActiveRecord::Base
attr_accessible :title
has_many :design_pictures, dependent: :destroy
has_many :images, :through => :design_pictures
validates :title, presence: true, length: { maximum: 60 }
end
应用程序/模型/design_picture.rb:
class DesignPicture < ActiveRecord::Base
attr_accessible :ranking
belongs_to :image
belongs_to :design
validates :image_id, presence: true
validates :design_id, presence: true
default_scope order: 'design_pictures.ranking ASC'
end
应用程序/模型/user.rb:
class User < ActiveRecord::Base
attr_accessible :name
has_many :designs, dependent: :destroy
has_many :images, dependent: :destroy
validates :name, presence: true, length: { maximum: 50 }
end
意见:
应用程序/视图/设计/show.html.erb:
<div>
<% if @design.design_pictures.any? %>
<h3>Images (<%= @design.design_pictures.count %>)</h3>
<ul>
<%= render @design_pictures %>
</ul>
<% end %>
</div>
<div>
<%= render 'shared/design_picture_form' %>
</div>
app/views/design_pictures/_design_picture.html.erb
<li>
<%= design_picture.image.title %> - Ranking: <%= design_picture.ranking %>
</li>
app/views/shared/_design_picture_form.html.erb:
<%= form_for(@design_picture) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :title, "Title" %>
<%= f.text_field :title,
placeholder: "Name your image.",
class: "" %>
<%= f.label :ranking, "Ranking" %>
<%= f.text_field :ranking,
placeholder: "Rank your design picture.",
class: "" %>
<%= hidden_field_tag(:design_id, @design.id) %>
<%= f.submit "Add Image", class: "btn btn-large btn-primary" %>
<% end %>
控制器:
应用程序/控制器/designs_controller.rb
def show
@design = Design.find(params[:id])
@design_pictures = @design.design_pictures.find(:all, :limit => 10)
@image = current_user.images.build
@design_picture = @design.design_pictures.build
end
应用程序/控制器/design_pictures_controller.rb
def create
@current_design = Design.find(params[:design_id])
@image = current_user.images.new(params[:title])
@design_picture = @current_design.design_pictures.build(:image_id => @image.id, params[:ranking])
if @design_picture.save
flash[:success] = "Micropost created!"
redirect_to @current_design
else
redirect_to designs_url
end
end
部分访问 design_picture 表单时出错:
undefined method `title' for #<DesignPicture image_id: nil, design_id: 1427, ranking: nil>
如果我从表单中删除标题,我可以提交表单但没有创建任何内容。
任何帮助将不胜感激。