2012-01-23 46 views
0

我有三個型號:得到父母的屬性在軌對象3.1

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 

我的模型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 

我的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 

在我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 

在我看來,新動作:

<%= 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 %> 

在選擇字段中板,可能或可能沒有已經分配的父類別。

我想擺脫類別(類別的此事件的名稱)在我的崗位查看屬性不使用選擇字段,或者輸入字段。

與此代碼在posts.controller.rb

if @board.category_id? 
    @post.category_id = @board.category_id 
end 

我在控制檯看到Post.first EJ:

<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"> 

如果我寫:

post = Post.first

post.board

我得到的目標板的罰款。這確實很好。

,但如果我寫:

崗位。類別

我得到:

=>零

我有嘗試針對新的崗位增加隱藏字段:

hidden_field(:category, :name) 

我怎樣才能得到物體類別的PARAMS ? 謝謝

回答

0

不要使用ID字段進行設置。取而代之的是在你的PostsController:

if @board.category_id? 
    @post.category_id = @board.category_id 
end 

試試這個行:

@post.category = @board.category 

這將設置@ post.category belongs_to關係指向@board.category假設它的存在(不爲零)。 Mongoid將爲您處理category_id字段的設置。 Read the mongoid documentation about relationships for a more detailed explanation.

+0

就是這樣。它工作正常:D非常感謝,:D – hyperrjas