I have three models:
category.rb
class Category
include Mongoid::Document
# Relationships
has_many :posts, :autosave => true
has_many :boards, :autosave => true
accepts_nested_attributes_for :boards
accepts_nested_attributes_for :posts
#fields
field :name
#attr
attr_accessible :name
end
My model board.rb
class Board
include Mongoid::Document
# Relationships
has_many :posts, :dependent => :destroy , :autosave => true
accepts_nested_attributes_for :posts
belongs_to :category
#fields
field :name
field :description
#attr
attr_accessible :name, :posts_attributes, :description, :category_id
end
My post.rb
class Post
include Mongoid::Document
# Relationships
belongs_to :board
belongs_to :category
belongs_to :user
#fields
field :content
#attr
attr_accessible :content :board_id, :category_id
end
In my posts_controller
def create
@post = current_user.posts.new(params[:post])
@board = @post.board
@board.user = current_user
if @board.category_id?
@post.category_id = @board.category_id
end
respond_to do |format|
if @post.save
format.html { redirect_to root_url, notice: 'Post was successfully created.' }
format.json { render json: root_url, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
In my view new action:
<%= form_for(@post) do |f| %>
<%= f.text_area :content %>
<%= f.collection_select :board_id, Board.where(:user_id => current_user.id), :id, :name%>
<%= f.submit :id => "button_submit_pin_edit" %>
<% end %>
The boards in select field, may or may not have a parent category already assigned.
I want get the attributes from category (the name of the category for this event) in my post view without using a select field, or an input field.
with this code in posts.controller.rb
if @board.category_id?
@post.category_id = @board.category_id
end
I see in my console for Post.first e.j.:
<Post _id: 4f1d96241d41c8280800007c, _type: nil, created_at: 2012-01-23 17:17:24 UTC, user_id: BSON::ObjectId('4f0b19691d41c80d08002b20'), board_id: BSON::ObjectId('4f1455fa1d41c83988000510'), category_id: BSON::ObjectId('4f1c2d811d41c8548e000008'), content: "nuevo post">
If I write:
post = Post.first
and
post.board
I get the object board fine. This does works fine.
but If I write:
post.category
I get:
=> nil
I have try in view new post add hidden field:
hidden_field(:category, :name)
How can I get the params of object category?
Thanks
Don’t set it using the ID fields. Instead of this in your PostsController:
Try this line:
Which will set the @post.category
belongs_torelationship to point to@board.categoryassuming it exists (is not nil). Mongoid will handle the setting of thecategory_idfield for you. Read the mongoid documentation about relationships for a more detailed explanation.