Ruby on rails新手在這裏。試圖創建一個初學者博客應用程序,並且遇到與我的模型之間存在多對多關聯的問題。Rails 4多對多協會不工作
我有2個模型 - 發佈,類別之間有多對多的關聯。
我的問題:當我創建一個新帖子時,帖子被保存,但後類別關聯不會保存在categories_posts表中。
我的代碼如下。
我很欣賞你對此的意見。
post.rb
class Post < ActiveRecord::Base
validates_presence_of :title, :body, :publish_date
belongs_to :user
has_and_belongs_to_many :categories
end
category.rb
class Category < ActiveRecord::Base
validates_presence_of :name
has_and_belongs_to_many :posts
end
categories_posts.rb
class CategoriesPosts < ActiveRecord::Base
end
遷移 - create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body
t.date :publish_date
t.integer :user_id
t.timestamps
end
end
end
遷移 - create_categories.rb
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
end
遷移 - create_categories_posts.rb
class CreateCategoriesPosts < ActiveRecord::Migration
def change
create_table :categories_posts do |t|
t.integer :category_id
t.integer :post_id
t.timestamps
end
end
end
柱控制器 - 創建和新方法
#GET /posts/new
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
#User id is not a form field and hence is not assigned in the view. It is assigned when control is transferred back here after Save is pressed
@post.user_id = current_user.id
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
後視圖(用於創建新郵):
<%= simple_form_for @post, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :title %>
<%= f.input :body %>
<%= f.input :publish_date %>
<%= f.association :categories, :as => :check_boxes %>
<div class="form-actions">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
posts_path, :class => 'btn' %>
</div>
<% end %>
個
謝謝, 邁克
我也有同樣的問題,在這裏找到了解決辦法:https://開頭計算器。com/questions/11480939/many-to-many-many-many-through-association-form-with-data-assigned-to-linking-m?answertab = active#tab-top – Eltaf