我在使用Rails 4创建记录时遇到问题。用户应该能够添加网址并以相同的形式为此网址选择特定的类别。问题是当我尝试添加网址及其类别时,它只保存网址而不是选择的类别。
每个用户都可以有多个网址,每个网址可以有多个类别。
class Url < ActiveRecord::Base
attr_accessible :url
belongs_to :user
has_and_belongs_to_many :categories
class Category < ActiveRecord::Base
has_and_belongs_to_many :urls
这是我添加新网址的表单
<%= form_for(@url) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.label :url %>
<%= f.text_field :url, placeholder: "Copy and Paste the url here" %>
</div>
<div>
<% Category.all.each do |category| %>
<div>
<%= check_box_tag "url[category_ids][]", category.id %>
<%= category.name %>
</div>
<% end %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
这是url控制器中的create方法
def create
@url = current_user.urls.build(params[:url])
if @url.save
flash[:success] = "Url added!"
render :template => "dashboard/index"
else
render :template => "dashboard/index"
end
end
正在保存网址,但您从复选框中选择的所有类别都不会随网址一起保存。我是否需要在Rails的创建方法中添加更多内容以实现我还要保存网址的类别?