我尝试使用 has_many到关系在两个不同的表格中保存数据,但只有一个视图但它无效:
我的控制器:
def new
@group = Group.new
@group.memberships.build
end
def create
@group = Group.new(group_params)
if @group.save
flash[:success] = "Group created!"
redirect_to @group
else
@feed_items = []
render 'groups/new'
end
end
def group_params
params[:group][:user_id] = current_user.id
params[:owner] = current_user.id
params.require(:group).permit(:user_id, :name, :category, :description, memberships_attributes: [:user_id, :group_id, :owner])
end
我的模特:
has_many :memberships
has_many :users, through: :memberships
has_many :posts
accepts_nested_attributes_for :memberships
我的表单:
<%= form_for(@group) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<% f.hidden_field :user_id %>
<%= f.text_area :name, placeholder: "Group's name", class: 'form-control' %>
<%= f.text_area :category, placeholder: "Category (i.e. #programming, #food, etc)", class: 'form-control' %>
<%= f.text_area :description, placeholder: "Description of the group", class: 'form-control' %>
</div>
<% f.fields_for :memberships do |mem| %>
<% mem.hidden_field :user_id %>
<% mem.hidden_field :group_id %>
<% mem.hidden_field :owner %>
<% end %>
<%= f.submit "Create", class: "btn btn-primary" %>
<% end %>
我的架构是:
create_table "groups", force: :cascade do |t|
t.integer "user_id"
t.string "name"
t.string "category"
t.text "description"
t.index ["user_id"], name: "index_groups_on_user_id"
end
create_table "memberships", force: :cascade do |t|
t.integer "user_id"
t.integer "group_id"
t.integer "owner"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_id"], name: "index_memberships_on_group_id"
t.index ["user_id"], name: "index_memberships_on_user_id"
end
有人可以帮我保存组内的用户信息以及会员资格表中的会员数据和组数据。
这是我的日志:
Started POST "/groups" for 127.0.0.1 at 2017-06-25 00:21:06 -0500
Processing by GroupsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"kOmM3x84+dbS+n4HkdnqMoX4NBlZYohUldCQdSAHJbge0+iAzGhX5KRPQG3sQ5bCV2NDqCCr3bFqvz/lBRChHg==", "group"=>{"name"=>"qqqqq", "category"=>"q", "description"=>"q"}, "commit"=>"Create"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
(0.0ms) begin transaction
Group Exists (0.5ms) SELECT 1 AS one FROM "groups" WHERE LOWER("groups"."name") = LOWER(?) LIMIT ? [["name", "qqqqq"], ["LIMIT", 1]]
SQL (1.5ms) INSERT INTO "groups" ("user_id", "name", "category", "description") VALUES (?, ?, ?, ?) [["user_id", 2], ["name", "qqqqq"], ["category", "q"], ["description", "q"]]
(12.3ms) commit transaction
Redirected to http://localhost:3000/groups/19
Completed 302 Found in 34ms (ActiveRecord: 14.8ms)