2011-05-23 19 views
1

私は他の2モデルに属しているモデルを使用しています。私はそれを作成しようとすると、私は両方のIDを取得するために管理しますが、コンテンツ自体はcontentは、データベース内のテキストとして設定されている、Rails - モデル作成の問題

def create 
    @person = Person.find(current_person) 
    @message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person)) 
    if @message.save 
     redirect_to(:back) 
    else 
     redirect_to(:back) 
    end 
    end 



<% form_for(:message, :url => messages_path(:person_id => current_person.id, :group_id => @group.id)) do |f| %> 
<%= f.text_area :content %> 
<%= f.submit "Submit" %> 
<%end %> 

また、データベースに格納されていないと私は、PostgreSQLを使用しています。

+0

モデルで 'create'メソッドを呼び出すと、モデルに保存されます。おそらく、新しいインスタンスを初期化するために 'new'を呼び出す必要があります。あるいは、 'create'メソッドが好きな人は' new_record? 'を使ってインスタンスが保存されているかどうかを確認します(検証の失敗など)。 – taro

答えて

2
@message = Message.create params[:message].merge(:group => Group.find(params[:group_id]), :person => Person.find(current_person)) 
0

@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person), :content => params[:content]

@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person)) 

を変更してみてください)

1

あなたのためにそれを行う必要があるのは、上記答える理由@。しかし、上記のステップを踏んで、関連の力を利用することができます。あなたのmessage.rbで

は、あなたが関連

class Message < ActiveRecord::Base 
    .. 
    belongs_to :group 
    belongs_to :person 
    ... 
end 

を持っているでしょうあなたはまたにhas_manyの関係を宣言し、グループ/個人モデルで同様の関連を持つことができます。 routes.rbを(Railsの2.3.x以降)

map.resources :group, :has_many => [:messages] 

class Group < ActiveRecord::Base 
    ... 
    has_many :messages 
    ... 
end 

class Person < ActiveRecord::Base 
    ... 
    has_many :messages 
    ... 
end 

routes.rbをで(Railsの3)

resources :groups do 
    resources :messages 
end 

これは、あなたのようなルートを提供します

POST group_messages_path(:group_id) # => this will route to 
            # MessagesController's create action 
            # and provide params[:group_id] 

あなたは現在のログイン関連のように見えるcurrent_personを使用していますので、urlやパラメータを使って表示または編集可能にすることはお勧めできません。 current_personは、作成アクション自体のセッションから派生する必要があります。

# form_for([@group,:message]) or form_for([@group,@message]) 
# automatically works out the path as POST /groups/:group_id/messages => MessagesController#create 
# And current person association remains safe to currently logged in person 
# without being revealed thru parameters and such. 

<% form_for([@group,@message]) do |f| %> 
    <%= f.text_area :content %> 
    <%= f.submit "Submit" %> 
<% end %> 


def create 
    @group = Group.find(params[:group_id]) 
    @person = current_person # or however you find current_person 
    @message = @group.messages.build(params[:messaage]) 
    @message.person = @person 
    if @message.save 
    redirect_to(:back) 
    else 
    redirect_to(:back) 
    end 
end