あなたのためにそれを行う必要があるのは、上記答える理由@。しかし、上記のステップを踏んで、関連の力を利用することができます。あなたの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
モデルで 'create'メソッドを呼び出すと、モデルに保存されます。おそらく、新しいインスタンスを初期化するために 'new'を呼び出す必要があります。あるいは、 'create'メソッドが好きな人は' new_record? 'を使ってインスタンスが保存されているかどうかを確認します(検証の失敗など)。 – taro