开发者

Question about editing by multiple Models and one controller

i have three Models(word,Adjectiv,Adverb) and one Controller(Words) that manage these Models.I have only one form,that user can add an adverb,an Adjectiv or a word. My edit function:

def edit
        @word开发者_JS百科=Word.find(params[:id])
        @adjektiv=Adjektiv.find(params[:id])
        @adverb =Adverb.find(params[:id])
  end 

for example when i want to edit one record of adverb (id=1) another records of adjectiv and Word with id=1 appear in Textboxes.I would like to be watched only the first record of adverb How can i do that? Thanks


This looks like a perfect situation to use STI (Single Table Inheritance) since adjektives and adverbs are words too. To achive this you will need an string field called type in your words table. Then you could do it like this:

def Word < ActiveRecord::Base
end

def Adjektiv < Word
end

def Adverb < Word
end

And then in your controller:

def edit
  @word=Word.find(params[:id])   
end 


If you have only one user form but multiple models, it means that you are associating multiple models with a single controller. Hence, it is advisable to go with a nested-model-form approach.

Please follow this excellent railscast by Ryan Bates on Nest Form-Model.

The link is for part 1 of the railscast, you can find subsequent railscast in the same website.

This approach will make your code cleaner, more efficient and easier to maintain.

Thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜