[英]Rails 4: checkbox and has_many through
楷模:
#models/user.rb
class User < ActiveRecord::Base
has_many :animals, through: :animal_users
has_many :animal_users
end
#models/animal.rb
class Animal < ActiveRecord::Base
has_many :users, through: :animal_users
has_many :animal_users
end
#models/animal_user.rb
class AnimalUser < ActiveRecord::Base
belongs_to :animal
belongs_to :user
end
用戶表格:
#views/users/_form.html.erb
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
# Checkbox part of the form that now works!
<div>
<% Animal.all.each do |animal| %>
<%= check_box_tag "user[animal_ids][]", animal.id, f.object.animals.include?(animal) %>
<%= animal.animal_name %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
users_controller.rb中的強大參數
def user_params
params.require(:user).permit(:name, animal_ids: [])
end
我遵循了此示例,但無法保存聯接表。 我在這里有兩個問題
目前,我正在像這樣保存它
def create
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'user was successfully created.' }
format.json { render json: @user, status: :created, location: @user}
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
而且這只會創建用戶,而不會創建聯接表。 我怎樣才能做到這一點?
@ user.save沒有傳遞嵌套屬性(animal_ids)
您需要像這樣傳遞參數:
@user = User.new(user_params)
在用戶模型(user.rb)中,您需要添加以下內容:
accepts_nested_attributes_for :animals
accepts_nested_attributes_for :animal_users
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.