【问题标题】:New and Create method in TOPIC controller if TOPIC belongs_to USER and FORUM如果 TOPIC 属于 USER 和 FORUM,则在 TOPIC 控制器中新建和创建方法
【发布时间】:2012-06-28 06:26:26
【问题描述】:

如果 TOPIC 属于 USER 和 FORUM,我想知道 TOPIC 的 newcreate 方法应该是什么样子。

class Forum < ActiveRecord::Base
  belongs_to :user
  has_many :topics, :dependent => :destroy
end

class User < ActiveRecord::Base
  has_many :forum
  has_many :topic
end

class Topic < ActiveRecord::Base
  belongs_to :user
  belongs_to :forum
end

当TOPIC只属于FORUM时,我使用了build这样的方法。

def new
  @forum = Forum.find(params[:forum_id])
  @topic = @forum.topics.build
end

def create
  @forum = Forum.find(params[:forum_id])
  @topic = @forum.topics.build(params[:topic])
  if @topic.save
    flash[:success] = "Success!"
    redirect_to topic_posts_path(@topic)
  else
    render 'new'
  end
end

但是现在TOPIC既属于FORUM又属于USER,不知道怎么办?关于这个话题有什么建议吗?

这是我的架构供参考。暂时忽略 POST。

create_table "forums", :force => true do |t|
  t.datetime "created_at",  :null => false
  t.datetime "updated_at",  :null => false
  t.string   "name"
  t.text     "description"
  t.integer  "user_id"
end

create_table "posts", :force => true do |t|
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
  t.integer  "topic_id"
  t.text     "content"
  t.integer  "user_id"
end

create_table "topics", :force => true do |t|
  t.datetime "created_at",   :null => false
  t.datetime "updated_at",   :null => false
  t.integer  "forum_id"
  t.string   "name"
  t.integer  "last_post_id"
  t.integer  "views"
  t.integer  "user_id"
end

create_table "users", :force => true do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at",                         :null => false
  t.datetime "updated_at",                         :null => false
  t.string   "password_digest"
  t.string   "remember_token"
  t.boolean  "admin",           :default => false
end

我对新 create 方法的解决方案

def create
  @forum = Forum.find(params[:forum_id])
  @topic = @forum.topics.build(params[:topic])
  @topic.user_id = current_user.id

  if @topic.save
    flash[:success] = "Success!"
    redirect_to topic_posts_path(@topic)
  else
    render 'new'
  end
end

current_user 返回当前用户对象。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations


    【解决方案1】:
    topic = Topic.new
    topic.forum = Forum.first
    topic.user = User.first
    
    topic = Topic.create(:forum => Forum.first, :user => User.first)
    
    topic = @user.topics.build(params[:topic])
    topic.forum = @forum
    
    etc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 2018-04-06
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多