ruby on rails - Saving records with has_many through relationship -
I have two models - the user and the keyword and a third model association which is the relationship between users and keywords. P>
I have a method method in the keyword controller that is shown below -
def create keyword = keyword. NY (keyword_params) if keyword. Fine_b (content: params [: content]). Zero? @ Keyword.save end @ keyword.associations.create (: user_id = & gt; current_user.id) Flash [: success] = "The keyword has been created successfully!" In the "create" method mentioned above, a user adds a keyword, so I am checking that the keyword is already present in the keyword table and if it is not, it saves. The keyword in the keyword table, and then it saves the connection between the organization and the table between the user and the keyword. However, when a keyword is already present in the keyword table (since it may have been added by another user), and says that a new user is adding this existing keyword to its list It gives me an error - "Skipping from @ keyword.save" on "@keywordpress.create" "Parents are not saved until you can make calls" (As the keyword first Only in database is).
I am using Rail 4 and Ruby 2.0.0
I am new to the rail and you can appreciate any help you can provide.
Update: Description of keyword model and keyword controller
Model: User model:
class user & lt; ActiveRecord :: Base before_save {self.email = email.downcase} Do the first: create_remember_token has_many: Associations has_many: Keywords, via = & gt; : Associations # Name Valid: Name, Attendance: Right, Length: {Max: 50} End
Keyword model:
class keyword < ActiveRecord :: Base has has_many: The question is has_many: Associations have_many: Users ,: By: = & gt; Association valid: content, presence: true, uniqueness: {case_ sensitive: false} expiration
association model
class association & lt; ActiveRecord :: Base is_to: keyword is_to: User valid: user_id ,: Specification = & gt; {: Area = & gt; : Keyword_id} End
Keyword Controller:
Category Keyword Controller & lt; ApplicationController before_action: sign_in_user, only: [: index, edit,: update, delete] def indefinitely @keywords = current_user.keywords.to_a end DEF new @keyword = keywords.New end DRF @ keyword = keyword.fund_b (Content: Counter [: Materials]) If @ keyword.nil? @ Keyword = keywords.credit (keyword_upm) end @ keyword.associations.create (: user_id => current_user.id) Flash [: success] = "The keyword has been created successfully!" End of End (- content)
You can write it like this:
def make @ keyword = keyword.phind_ (content: params [: content]) If @ keyword.nil? @ Keyword = keywords.credit (keyword_upm) end @ keyword.associations.create (: user_id => current_user.id) Flash [: success] = "The keyword has been created successfully!" Redirect_to keywords_path
Comments
Post a Comment