从rails 3.1中的父对象获取属性

时间:2012-01-23 18:09:48

标签: ruby-on-rails ruby-on-rails-3 mongoid nested-forms

我有三种模式:

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

选择字段中的电路板可能已经或可能没有已分配的父类别。

我希望在我的帖子视图中从类别(此事件的类别名称) 获取属性,而不使用选择字段或输入字段。< / p>

posts.controller.rb

中使用此代码
if @board.category_id? 
  @post.category_id = @board.category_id
 end

我在我的控制台中看到 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"> 

如果我写:

post = Post.first

post.board

我把对象板弄好了。这确实很好。

但如果我写:

post.category

我明白了:

=&GT;零

我已尝试查看新帖子添加隐藏字段:

hidden_field(:category, :name)

如何获取对象类别的参数? 感谢

1 个答案:

答案 0 :(得分:0)

请勿使用ID字段进行设置。而不是在你的PostsController中:

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

试试这一行:

@post.category = @board.category

假设它存在(不是nil),那么将@ post.category belongs_to关系设置为指向@board.category。 Mongoid将为您处理category_id字段的设置。 Read the mongoid documentation about relationships for a more detailed explanation.