【发布时间】:2015-01-07 01:38:52
【问题描述】:
我有 3 个具有 has_many through 关系的模型:Food(例如:Chocolate)、Sub(巧克力食品替代品)、Joint(联合表)。
说@food = Food.find(1); has_many through 关系允许我执行@subs = @food.subs,它返回与@food 关联的所有替代品。这工作正常,但是只有 Sub id 被保存,而不是它的属性,即 :name 和 :description 因为你可以看到它在我的控制器的创建操作中保存 @food.subs 时返回 nil:
=> #<ActiveRecord::Associations::CollectionProxy [#<Sub id: 28,name:nil,description:nil,created_at:
"2015-01-07 00:40:35", updated_at: "2015-01-07 00:40:35">]>
我想问题出在我的食物控制器中的创建操作上,也可能与我的嵌套表单有关。我花了无数个小时试图弄清楚这一点,我非常渴望找到答案。我真的不知道该去哪里找了。 我是 Rails 新手,非常感谢您的帮助和时间,非常感谢。如果可能,请根据我的初学者水平调整您的答案:-)。
下面是我的控制器、表单和相关信息的示例。
这是我的模型:
class Food < ActiveRecord::Base
has_many :joints
has_many :subs, :through => :joints
accepts_nested_attributes_for :subs
end
class Sub < ActiveRecord::Base
has_many :joints
has_many :foods, :through => :joints
accepts_nested_attributes_for :foods
end
class Joint < ActiveRecord::Base
belongs_to :food
belongs_to :sub
end
这是我的 db-schema 仅供参考:
create_table "foods", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "joints", force: true do |t|
t.integer "food_id"
t.integer "sub_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "subs", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
这是我的 foods_controller:
def new
@food = Food.new
@sub = Sub.new
end
def create
@food = Food.new(food_params)
@food.subs.build(params[:subs])
@food.save
respond_to do |format|
if @food.save
format.html { redirect_to @food, notice: 'Food was successfully created.' }
format.json { render :show, status: :created, location: @food }
else
format.html { render :new }
format.json { render json: @food.errors, status: :unprocessable_entity }
end
end
end
private
def food_params
params.require(:food).permit(:name, :description, subs_attributes: [:name, :description])
end
end
这是我的观点/食物/_form:
<%= form_for(@food) do |f| %>
<% if @food.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@food.errors.count, "error") %> prohibited this food from being saved:</h2>
<ul>
<% @food.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div>
<%= f.fields_for(@sub) do |sub| %>
<div class="field">
<%= sub.label :name %>
<%= sub.text_field :name %>
</div>
<div class="field">
<%= sub.label :description %>
<%= sub.text_area :description %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的路线以防万一: 资源:食物
resources :subs
resources :joints
root "foods#index"
非常感谢!
安托万。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-attributes has-many-through