Ruby on 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
Post Controller - создавать и новые методы
#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: // StackOverflow.com/questions/11480939/many-to-many-has-many-through-association-form-with-data-assign-to-linking-m? answertab = active # tab-top – Eltaf